Contents
Parse Phone Number
You can parse a phone number present in string into a PhoneNumber object using phonenumbers.parse() function.
Pass the string to phonenumbers.parse() function, and it returns a PhoneNumber object.
Examples
1. Parse the phone number “+442083661177”
In the following program, we have a phone number string in variable phonenumber_string. We parse this string into a PhoneNumber object using phonenumbers.parse() function and store the object in x.
Python Program
import phonenumbers
phonenumber_string = "+442083661177"
x = phonenumbers.parse(phonenumber_string)
print(x)
Run Code CopyOutput
Country Code: 44 National Number: 2083661177
We can also read the following properties from the PhoneNumber object.
- country_code
- national_number
- extension
- italian_leading_zero
- number_of_leading_zeros
- raw_input
- country_code_source
- preferred_domestic_carrier_code
2. Get country code and other info
For example, in the following program, we print the country code, and number of leading zeros in the phone number.
Python Program
import phonenumbers
# Phone number in a string
phonenumber_string = "+442083661177"
# Parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)
print('Country code :', x.country_code)
print('Number of leading zeros :', x.number_of_leading_zeros)
Run Code CopyOutput
Country code : 44
Number of leading zeros : None
Summary
In this tutorial of Python Examples, we learned how to parse a given phone number in a string to a PhoneNumber object using phonenumbers library, with the help of example programs.