Akyna
Akyna

Reputation: 87

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 ?

Upvotes: 3

Views: 4942

Answers (3)

Yuval.R
Yuval.R

Reputation: 1306

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

Upvotes: 3

TOE703
TOE703

Reputation: 53

You could use country_converter, install with pip install country_converter.
This is around 50kb compared to pycountry being around 10mb.

Conversion is easy with something like:

import country_converter as coco
input_country = input(" Please choose a contry tagg (like fr, us...) :")
converted_country = coco.convert(names=input_country, to="name")
print(converted_country)
  • names can be singular or a list which can be mixed input
    • names="fr"
    • names=["fr", "USA", "826", 276, "China"]

There are a lot of classification schemes listed in the documentation that can be taken as inputs or converted to .

Upvotes: 4

Kirk Strauser
Kirk Strauser

Reputation: 30933

This is referred to as "internationalization", and the Python module for doing this is gettext. For example:

In order to prepare your code for I18N, you need to look at all the strings in your files. Any string that needs to be translated should be marked by wrapping it in _('...') — that is, a call to the function _(). For example:

filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
    fp.write(message)

This is a complex subject and that page will give you a lot of information to start with.

Upvotes: 0

Related Questions