This article will teach you how to use Python to determine the country of a phone number using Python.
How to Get Country From Phone Number in Python using Phonenumbers Module
The phonenumbers module is a python package that can be used to find the country corresponding to a phone number based on its phone code. It can also discover basic information about a phone number, provider, area, etc.
To begin with, we must install the module in our system. This can be done by typing the following command into your terminal:
pip install phonenumbers
Then, we will import that module and use the description_for_number method of its geocoder class. The complete code is shown below.
Python3
# importing module phonenumbers import phonenumbers as pn # importing geocoder from phonenumbers from phonenumbers import geocoder # input phone number with country code phoneNumber = "+9193**234567" phoneNumber = pn.parse(phoneNumber) # printing the required country for that phone number print (geocoder.description_for_number(phoneNumber, "en" )) |
Output:
India
How to Get Country From Phone Number in Python using pycountry and region_code_for_number
This method uses the region_code_for_number of the phonenumbers module to find the country code of the phonenumbers. However, to find the country name from the country code we will need to use the pycountry Python module.
To use the pycountry module, we first need to install it. This can easily be done using the following command:
pip install pycountry
A simple implementation of this method can be seen below:
Python3
import pycountry , phonenumbers from phonenumbers.phonenumberutil import region_code_for_number pn = phonenumbers.parse( '+919**1234567' ) country = pycountry.countries.get(alpha_2 = region_code_for_number(pn)) print (country.name) |
Output:
India
How to Get Country From Phone Number in Python using phone-iso3166 Module
Firstly, you have to install the phone-iso3166 module into your system.
pip install phone-iso3166
We can find Country From Phone Number in Python using the phone_country method. It takes the phone number as input and outputs its country code. Therefore, similarly to the previous method, we can use the pycountry module to get the country name from the country code. This can be seen in the code below:
Python3
from phone_iso3166.country import * import pycountry c = phone_country( '+919**1234567' ) country = pycountry.countries.get(alpha_2 = c) print (country.name) |
Output:
India