0
# Core Parsing and Formatting
1
2
Essential functions for parsing phone number strings into structured objects and formatting them for display or storage. These functions form the foundation of phonenumberslite's functionality.
3
4
## Capabilities
5
6
### Phone Number Parsing
7
8
Parse phone number strings with various input formats, handling international prefixes, national formats, and region-specific patterns.
9
10
```python { .api }
11
def parse(number: str, region: str = None, keep_raw_input: bool = False,
12
numobj: PhoneNumber = None, _check_region: bool = True) -> PhoneNumber:
13
"""
14
Parse a phone number string and return a PhoneNumber object.
15
16
Parameters:
17
- number: The phone number string to parse
18
- region: Two-letter region code (ISO 3166-1 alpha-2) for context when parsing national numbers
19
- keep_raw_input: Whether to store the raw input string in the PhoneNumber object
20
- numobj: Optional PhoneNumber object to reuse instead of creating new one
21
- _check_region: Internal parameter for region validation (default True)
22
23
Returns:
24
PhoneNumber object with parsed components
25
26
Raises:
27
NumberParseException: If number cannot be parsed
28
"""
29
```
30
31
**Usage Examples:**
32
33
```python
34
import phonenumbers
35
36
# Parse international number with country code
37
number = phonenumbers.parse("+442083661177")
38
39
# Parse national number with region context
40
uk_number = phonenumbers.parse("020 8366 1177", "GB")
41
42
# Parse with raw input preservation
43
number_with_raw = phonenumbers.parse("+44 (20) 8366-1177", keep_raw_input=True)
44
45
# Handle parsing errors
46
try:
47
invalid = phonenumbers.parse("invalid", "US")
48
except phonenumbers.NumberParseException as e:
49
print(f"Parse error: {e}")
50
```
51
52
### Standard Number Formatting
53
54
Format parsed phone numbers using standard international formats for display, storage, or dialing purposes.
55
56
```python { .api }
57
def format_number(numobj: PhoneNumber, num_format: PhoneNumberFormat) -> str:
58
"""
59
Format a phone number according to the specified format.
60
61
Parameters:
62
- numobj: PhoneNumber object to format
63
- num_format: Formatting style (E164, INTERNATIONAL, NATIONAL, RFC3966)
64
65
Returns:
66
Formatted phone number string
67
"""
68
```
69
70
**Usage Examples:**
71
72
```python
73
import phonenumbers
74
from phonenumbers import PhoneNumberFormat
75
76
number = phonenumbers.parse("+442083661177")
77
78
# E164 format (for storage/APIs)
79
e164 = phonenumbers.format_number(number, PhoneNumberFormat.E164)
80
# "+442083661177"
81
82
# International format (for international display)
83
intl = phonenumbers.format_number(number, PhoneNumberFormat.INTERNATIONAL)
84
# "+44 20 8366 1177"
85
86
# National format (for domestic display)
87
national = phonenumbers.format_number(number, PhoneNumberFormat.NATIONAL)
88
# "020 8366 1177"
89
90
# RFC3966 format (for tel: URIs)
91
rfc = phonenumbers.format_number(number, PhoneNumberFormat.RFC3966)
92
# "tel:+44-20-8366-1177"
93
```
94
95
### Custom Pattern Formatting
96
97
Format numbers using custom formatting patterns for specialized display requirements.
98
99
```python { .api }
100
def format_by_pattern(numobj: PhoneNumber, num_format: PhoneNumberFormat,
101
user_defined_formats: list) -> str:
102
"""
103
Format a number using user-defined formatting patterns.
104
105
Parameters:
106
- numobj: PhoneNumber object to format
107
- num_format: Base formatting style
108
- user_defined_formats: List of NumberFormat objects with custom patterns
109
110
Returns:
111
Formatted number string using custom patterns
112
"""
113
```
114
115
### Original Format Preservation
116
117
Format numbers while attempting to preserve the original formatting structure when possible.
118
119
```python { .api }
120
def format_in_original_format(numobj: PhoneNumber, region_calling_from: str) -> str:
121
"""
122
Format number preserving original formatting where possible.
123
124
Parameters:
125
- numobj: PhoneNumber object (must have been parsed with keep_raw_input=True)
126
- region_calling_from: Region code for formatting context
127
128
Returns:
129
Number formatted to match original input structure
130
"""
131
```
132
133
### Carrier Code Formatting
134
135
Format national numbers with carrier code information for regions that support carrier selection.
136
137
```python { .api }
138
def format_national_number_with_carrier_code(numobj: PhoneNumber,
139
carrier_code: str) -> str:
140
"""
141
Format national number including carrier code.
142
143
Parameters:
144
- numobj: PhoneNumber object to format
145
- carrier_code: Carrier code to include in formatting
146
147
Returns:
148
National format string with carrier code
149
"""
150
151
def format_national_number_with_preferred_carrier_code(numobj: PhoneNumber,
152
fallback_carrier_code: str) -> str:
153
"""
154
Format using preferred carrier code or fallback.
155
156
Parameters:
157
- numobj: PhoneNumber with potential preferred carrier code
158
- fallback_carrier_code: Carrier code to use if none preferred
159
160
Returns:
161
National format with appropriate carrier code
162
"""
163
```
164
165
### Mobile Dialing Format
166
167
Format numbers optimized for mobile dialing from specific regions, handling international prefixes and local conventions.
168
169
```python { .api }
170
def format_number_for_mobile_dialing(numobj: PhoneNumber, region_calling_from: str,
171
with_formatting: bool = False) -> str:
172
"""
173
Format number for mobile dialing from specified region.
174
175
Parameters:
176
- numobj: PhoneNumber to format for dialing
177
- region_calling_from: Region from which the call will be made
178
- with_formatting: Whether to include spacing and punctuation
179
180
Returns:
181
Number formatted for mobile dialing, or empty string if not dialable
182
"""
183
```
184
185
### International Dialing Format
186
187
Format numbers for dialing from international locations, handling various international prefix patterns.
188
189
```python { .api }
190
def format_out_of_country_calling_number(numobj: PhoneNumber,
191
region_calling_from: str) -> str:
192
"""
193
Format number for international dialing from specified region.
194
195
Parameters:
196
- numobj: PhoneNumber to format
197
- region_calling_from: Region code for the calling location
198
199
Returns:
200
Number formatted with appropriate international prefix
201
"""
202
203
def format_out_of_country_keeping_alpha_chars(numobj: PhoneNumber,
204
region_calling_from: str) -> str:
205
"""
206
Format for international dialing while preserving alpha characters.
207
208
Parameters:
209
- numobj: PhoneNumber containing alpha characters
210
- region_calling_from: Calling region code
211
212
Returns:
213
Formatted number retaining alpha characters where appropriate
214
"""
215
```
216
217
## Usage Patterns
218
219
### Basic Parsing and Formatting Workflow
220
221
```python
222
import phonenumbers
223
from phonenumbers import PhoneNumberFormat
224
225
# Parse various input formats
226
numbers = [
227
"+1-800-555-1234", # International with formatting
228
"800.555.1234", # National with dots
229
"(800) 555-1234", # National with parentheses
230
"18005551234", # International without formatting
231
]
232
233
for number_string in numbers:
234
try:
235
# Parse with US context for national numbers
236
parsed = phonenumbers.parse(number_string, "US")
237
238
# Format for different purposes
239
for_storage = phonenumbers.format_number(parsed, PhoneNumberFormat.E164)
240
for_display = phonenumbers.format_number(parsed, PhoneNumberFormat.INTERNATIONAL)
241
242
print(f"Input: {number_string}")
243
print(f"Storage: {for_storage}")
244
print(f"Display: {for_display}")
245
print()
246
247
except phonenumbers.NumberParseException as e:
248
print(f"Failed to parse {number_string}: {e}")
249
```
250
251
### Regional Context Handling
252
253
```python
254
import phonenumbers
255
256
# Same number string, different regional contexts
257
national_number = "020 8366 1177"
258
259
# Parse as UK number
260
uk_number = phonenumbers.parse(national_number, "GB")
261
print(f"UK: {phonenumbers.format_number(uk_number, PhoneNumberFormat.E164)}")
262
263
# Parsing without region context would fail for national format
264
try:
265
no_region = phonenumbers.parse(national_number, None)
266
except phonenumbers.NumberParseException:
267
print("National number requires region context")
268
```