How to Find Country Name of a Phone Number from Country Code in Python?

In this post, let us see how to use Python to determine the country of a phone number based on its country code. It’s pretty simple and straightforward, with only a few lines of code.

Here we will use the python phonenumbers module to identify the country corresponding to their phone number attached with the phone code. The phonenumbers module is used to obtain basic information about the phone number, carrier, region, and so on.

Before we work with this phonenumbers module we must first install it in our system.

Installation:

pip install phonenumbers

Find Country Name of a Phone Number from Country Code in Python

Below are the ways to find the country name of the given phone number using the country code:

Method #1: Using phonenumbers Module

Approach:

  • Import phonenumbers module using the import keyword
  • Import geocoder from phonenumbers module using the import keyword
  • Give some random phone number along with the country code as user input using the input() function and store it in a variable.
  • Pass the above-given phone number as an argument to the parse() function to process the given phone number and store it in the same variable.
  • Print the corresponding country name for the given phone number using the description_for_number() function by passing phone number, “en” as arguments to it.
  • The Exit of the Program.

Below is the implementation:

# Import phonenumbers module using the import keyword
import phonenumbers as pn
# Import geocoder from phonenumbers module using the import keyword
from phonenumbers import geocoder

# Give some random phone number along with the country code as user input
# using the input() function and store it in a variable.
gvn_phonenum = input("Give some random phone number along with the country code: ")
# Pass the above given phone number as an argument to the parse() function
# to process the given phone number and store it in the same variable.
gvn_phonenum = pn.parse(gvn_phonenum)

# Print the corresponding country name for the given phone number using the 
# description_for_number() function by passing phone number, "en" as arguments to it.
print(geocoder.description_for_number(gvn_phonenum, "en"))

Output:

Give some random phone number along with the country code: +919494580181
India

Method #2: Using phone-iso3166 module

Install the phone-iso3166 module using the below syntax:

pip install phone-iso3166

Approach:

  • Import the phone-iso3166 module using the import keyword.
  • Pass the phone number to the phone_country() function and print the result
  • The Exit of the Program.

Below is the Implementation:

#Import the phone-iso3166 module using the import keyword.
from phone_iso3166.country import *
#Pass the phone number to the phone_country() function and print the result
res = phone_country('+91 9578457739')
print(res)

Output:

IN