首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是打印异常的输出,为什么它与输出的字符串不匹配?

什么是打印异常的输出,为什么它与输出的字符串不匹配?
EN

Stack Overflow用户
提问于 2020-12-02 18:14:00
回答 1查看 46关注 0票数 2

在以下代码块中:

代码语言:javascript
复制
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

谁能解释一下这是怎么回事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-02 18:18:51

前两个print语句打印'tomato',包括单引号,这意味着引号实际上是字符串的一部分。

将if语句更改为:

代码语言:javascript
复制
if str(e) == "'tomato'":
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65113810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档