Get country code from phone number
To get country code from given phone number, parse the phone number to a PhoneNumber object, and read the country_code property.
PhoneNumber.country_code
Example
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. Then we access the country_code property of this PhoneNumber object.
Python Program
import phonenumbers
#phone number in a string
phonenumber_string = "+442083661177"
#parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)
#get country code
code = x.country_code
print('Country code :', code)
Output
Country code : 44
Summary
In this tutorial of Python Examples, we learned how to get country code from given phone number using phonenumbers library, with the help of example programs.