pythoncountry-codesiso-3166

How do I get the country name from a given ISO-3166-1 alpha-2 code in Python?


I want the user to input a ISO-3166-1 alpha-2 code.

country_code = input("Please enter a country's two-letter code (e.g. FR, US) :")

I then want to translate the code into the country's name:

FR -> France
US -> United States of America

https://laendercode.net/en/2-letter-list.html

How can I do this ?


Solution

  • You can try the module pycountry, in the command line run pip install pycountry, and then in your code:

    import pycountry
    country_code = input("Please choose a country tag (like fr, us...): ")
    country = pycountry.countries.get(alpha_2=country_code)
    country_name = country.name
    

    For more info see this