python - print 异常的输出是什么以及为什么它与输出的字符串不匹配

标签 python python-3.x

在以下代码块中:

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/

相关文章:

python - 为什么我在 python 中出现不受支持的操作数类型错误

python-3.x - 如何在tensorflow 2 Tensorflow 2/Keras中制作自定义validation_step?

python - cx_Oracle : Error 933. ORA-00933 : “SQL command not properly ended” : SQL command error?

python-3.x - 在 ffmpeg 命令上映射 3 个或更多输出

python - 烦人的生成器错误

python - 网页抓取错误: Request and No Connection

Python C API - 如何从 PyObject 构造对象

python - 绘图铅笔断了

python - 从其中包含 return <value> 语句的生成器中产生

python - 检查字符串是否不是反序列化的 json 或 python 中的列表