Python – Get Country Name from Phone Number

Get country name from phone number

To get country name from given phone number

  1. Using phonenumbers library: parse the phone number to a PhoneNumber object, and read the country_code property. From this country code, get the region code using region_code_for_country_code() function.
  2. Using pycountry library: pass the country code as argument to pycountry.countries.get() method and get the Country object. From this Country object, get the name property.

Examples

1. Get country name from given phone number string

In the following program, we have a phone number string in variable phonenumber_string.

We get the country name from this string using phonenumbers library and pycountry library.

Python Program

import phonenumbers
import pycountry

# Take phone number in a string
phonenumber_string = "+442083661177"

# Parse the string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)
print('Country code :', x.country_code)

# Get region code
region_code = phonenumbers.region_code_for_country_code(x.country_code)
print('Region code  :', region_code)

# Get country name
country = pycountry.countries.get(alpha_2=region_code)
name = country.name
print('Country name :', name)
Run Code Copy

Output

Country code : 44
Region code  : GB
Country name : United Kingdom

Summary

In this tutorial of Python Examples, we learned how to get country name from given phone number using phonenumbers library and pycountry library, with the help of example programs.

Related Tutorials

Code copied to clipboard successfully 👍