[英]Try / except not working with a specific exception in Python
我正在嘗試使用 try / except 解決代碼中庫 (pycountry_convert) 的特定錯誤,但是當我使用 except 來避免這種情況時,它就不起作用了。 我已經嘗試了很多事情來解決這個問題。
這是代碼
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
在東帝汶的情況下,此代碼返回“N/A”,而它應該返回“AS”。 我已經嘗試在引號前使用“”,從字符串中刪除所有特殊字符,但它不起作用,我感到非常沮喪。
我試着做類似下圖的事情來查看我的字符串中是否有任何拼寫錯誤或其他東西,但它在 try/except 之外工作
我剛剛找到了答案,盡管我不明白。 在這里找到了我的問題的解決方案。
我不知道為什么,但是當我使用repr(e) == "KeyError(\"Invalid Country Alpha-2 code: \'TL\'\")"
而不是e == "\"Invalid Country Alpha-2 code: \'TL\'\""
它有效。 如果有人能向我解釋為什么我不能認為 python 只是討厭我,我將不勝感激。
感謝@mace 和@ThomasWeller 試圖幫助我:)
我已經調查了你的問題,這有點棘手,因為額外的引號 "" 被添加到異常字符串中。
我已將您的代碼壓縮到問題部分並打印 3 種不同的方式來查看異常 e。
import pycountry_convert as pc
country_code = 'TL'
print(" hello")
try:
continent_name = pc.country_alpha2_to_continent_code(country_code)
except Exception as e:
print(f'type e - {type(e)} value {e}')
print(f'type str(e) - {type(str(e))} value {str(e)}')
print(f'type repr(e) - {type(repr(e))} value {repr(e)}')
if e == '"Invalid Country Alpha-2 code: \'TL\'"':
print("TRUE 1")
else:
print("FALSE 1")
if str(e) == '"Invalid Country Alpha-2 code: \'TL\'"':
print("TRUE 2")
else:
print("FALSE 2")
if repr(e) == "KeyError(\"Invalid Country Alpha-2 code: \'TL\'\")":
print("TRUE 3")
else:
print("FALSE 3")
這是 output:
hello
type e - <class 'KeyError'> value "Invalid Country Alpha-2 code: 'TL'"
type str(e) - <class 'str'> value "Invalid Country Alpha-2 code: 'TL'"
type repr(e) - <class 'str'> value KeyError("Invalid Country Alpha-2 code: 'TL'")
FALSE 1
TRUE 2
TRUE 3
您可以看到的第一件事是“hello”打印時沒有引號,但 e-values 打印時帶有引號。 所以在電子信息/字符串周圍有額外的“”。 在您的第一個代碼中,它們丟失了(“無效...\'TL\'”),但在您的答案代碼中它們被放置在字符串周圍(“\”無效... \'TL\'\“”)。
您在我的示例 output 中還可以看到,e 的類型為“KeyError”。
您不能將類型“KeyError”與類型字符串進行比較。 因此,在比較之前,您必須使用 str(e) 將 e 轉換/更改為字符串。
您還可以使用 repr(e) 也可以將 e“轉換”為字符串。 但這會在字符串中添加額外的“KeyError(...”。
最接近您的初始代碼的解決方案是
# Special Case: Timor Leste
if str(e) == '"Invalid Country Alpha-2 code: \'TL\'"':
它將 e 更改為一個字符串並在您的初始字符串周圍添加額外的引號 "" 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.