[Python] Script that finds country code from a capital city

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I want to write the script that transforms

    "London" to "London,uk"
    "Barcelona" to "Barcelona,es"


    I have a list of a cities and want to get the code of a country to then append it.

    I tried:

    import pycountry

    capital = input("Capital city ")

    country_code = None

    for country in pycountry.countries:
    try:
    capital_name = country.capital
    if capital_name and capital_name.lower() == capital.lower():
    country_code = country.alpha_2
    break
    except AttributeError:
    continue


    but it doesn't work.

    Continue reading...

Compartilhe esta Página