I'm trying to solve a specific error from a library (pycountry_convert) in a code with try / except, but when I use the except to avoid this case it just doesn't work. I've tried so many things to solve this.
Here is the code
import pycountry_convert as pc
def pegacontinente(nomepais):
nomepais = nomepais.replace("-", " ")
e = ['and', 'the']
nomepais = ' '.join([word.capitalize() if word not in e else word for word in nomepais.split()])
country_code = pc.country_name_to_country_alpha2(nomepais, cn_name_format="default")
try:
continent_name = pc.country_alpha2_to_continent_code(country_code)
except Exception as e:
# Special Case: Timor Leste
if e == "Invalid Country Alpha-2 code: \'TL\'":
continent_name = 'AS'
else:
continent_name = 'N/A'
return continent_name
In the case of Timor Leste, this code returns "N/A", when it's suppose to return 'AS'. I already tried to use "" before quote marks, remove all special characters from the string but it just don't work and I'm getting very frustrated.
I tried to do something like the image below to see if there is any typo at my string or something but it works out of the try/except thing
I just found the answer even though I didn't understand it. The solution for my problem found here .
I don't know why but when I use
repr(e) == "KeyError(\"Invalid Country Alpha-2 code: \'TL\'\")"
instead ofe == "\"Invalid Country Alpha-2 code: \'TL\'\""
it works. If any person could explain me why so I can't think that python just hates me I would be greatful.Thanks for @mace and @ThomasWeller that tried to help me :)