Get country name from country code in python?

I worked with 2 python libraries: phonenumbers , pycountry . I really could not find a way to indicate the country code and get the corresponding country name.

In phonenumbers you need to provide full parse numbers. In pycountry it just gets the ISO of the country.

Is there any solution or way to provide the country code of the library in any way and get the name of the country?

+5
source share
1 answer

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

PhoneNumberUtilTest unittests seems to cover your specific use case; mapping a country phone number to a given region using the getRegionCodeForCountryCode() function. There is also a getRegionCodeForNumber() function that first retrieves the parsing country code attribute.

And indeed, there are corresponding phonenumbers.phonenumberutil.region_code_for_country_code() and phonenumbers.phonenumberutil.region_code_for_number() 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 it directly in pycountry :

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

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

 >>> region_code_for_country_code(1) 'US' >>> region_code_for_country_code(44) 'GB' 
+15
source

All Articles