Alireza
Alireza

Reputation: 6848

Get country name from Country code in python?

I have worked with 2 python libraries: phonenumbers, pycountry. I actually could not find a way to give just country code and get its corresponding country name.

In phonenumbers you need to provide full numbers to parse. In pycountry it just get country ISO.

Is there a solution or a method in any way to give the library country code and get country name?

Upvotes: 21

Views: 35170

Answers (3)

Ivan Sidaruk
Ivan Sidaruk

Reputation: 455

Not sure why nobody has written about phone-iso3166 so far, but actually this does the work:

>>> from phone_iso3166.country import *
>>> phone_country(45)
'DK'
>>> phone_country('+1 202-456-1111')
'US'
>>> phone_country(14412921234)
'BM'

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121226

The phonenumbers library is rather under-documented; instead they advice you to look at the original Google project for unittests to learn about functionality.

The PhoneNumberUtilTest unittests seems to cover your specific use-case; mapping the country portion of a phone number to a given region, using the getRegionCodeForCountryCode() function. There is also a getRegionCodeForNumber() function that appears to extract the country code attribute of a parsed number first.

And indeed, there are corresponding phonenumbers.phonenumberutil.region_code_for_country_code() and phonenumbers.phonenumberutil.region_code_for_number() functions to do the same in Python:

import phonenumbers
from phonenumbers.phonenumberutil import (
    region_code_for_country_code,
    region_code_for_number,
)

pn = phonenumbers.parse('+442083661177')
print(region_code_for_country_code(pn.country_code))

Demo:

>>> import phonenumbers
>>> from phonenumbers.phonenumberutil import region_code_for_country_code
>>> from phonenumbers.phonenumberutil import region_code_for_number
>>> pn = phonenumbers.parse('+442083661177')
>>> print(region_code_for_country_code(pn.country_code))
GB
>>> print(region_code_for_number(pn))
GB

The resulting region code is a 2-letter ISO code, so you can use that directly in pycountry:

>>> import pycountry
>>> country = pycountry.countries.get(alpha_2=region_code_for_number(pn))
>>> print(country.name)
United Kingdom

Note that the .country_code attribute is just an integer, so you can use phonenumbers.phonenumberutil.region_code_for_country_code() without a phone number, just a country code:

>>> region_code_for_country_code(1)
'US'
>>> region_code_for_country_code(44)
'GB'

Upvotes: 46

valex
valex

Reputation: 5769

Small addition - you also can get country prefix by string code. E.g.:

from phonenumbers.phonenumberutil import country_code_for_region

print(country_code_for_region('RU'))
print(country_code_for_region('DE'))

Upvotes: 2

Related Questions