在以下代码块中:
dictionary = dict()
dictionary[0] = {}
try:
print(dictionary[0]["tomato"])
except Exception as e:
print(e) # prints 'tomato'
print(str(e)) # prints 'tomato'
if str(e) == 'tomato':
print("Not tomato") # never prints, why?
即使 print(e)
打印 'tomato'
,str(e) == 'tomato'
也不是 True
有人可以解释一下这是怎么回事吗?
最佳答案
前两个打印语句打印 'tomato'
包括单引号,因此这意味着引号实际上是字符串的一部分。
将 if 语句更改为:
if str(e) == "'tomato'":
关于python - print 异常的输出是什么以及为什么它与输出的字符串不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65113810/