简体   繁体   English

为什么 bool("0") 在 python 中为真? 为什么会这样?

[英]Why bool("0") is true in python? why does this happen?

当我最近开始学习 Python 时,我遇到了这个布尔概念并执行了这个表达式bool("0") ,但是我得到了一个令人困惑的结果,因为这个表达式是True ,谁能告诉我为什么会发生这种情况。

bool("0") evaluates to True because "0" in this case is a non-empty string. bool("0")计算结果为 True,因为在这种情况下"0"是一个非空字符串。 It's useful for things like :它对以下内容很有用:

if str: #check if str is not empty
    #do something

bool(0) on the other hand evaluates to False.另一方面, bool(0)的计算结果为 False。

这是因为它将为每个非空字符串、列表等返回 True。

如果 int 类型变量为零,解释器将其显示为 False .bool("0") 计算结果为 True,因为在这种情况下,"0" 是一个非空字符串,而不是 int在一张照片中完整查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM