gpt4 book ai didi

python - 理解字符串的真实性

转载 作者:行者123 更新时间:2023-11-30 22:19:46 25 4
gpt4 key购买 nike

据我所知,Python 内置类型具有“真实性”值,空字符串被视为 False,而任何非空字符串都被视为 True

这是有道理的

我可以使用内置函数 bool 来检查这一点。

>>> bool("")
False

>>> bool("dog")
True

在使用条件时,我还可以利用这些真实值。例如:

>>> if "dog":
... print("yes")
...
yes

这很令人困惑

但这不适用于 == 运算符:

>>> "dog" == True
False

>>> "dog" == False
False

任何人都可以解释为什么 == 似乎与条件语句的行为不同?

最佳答案

请参阅truth value testingcomparisons文档的各个部分,摘录如下。

简而言之,默认情况下大多数事情都是真的,这就是为什么 bool("dog") 是真的。 == 运算符比较两个对象的相等性,而不是比较它们的真实性,正如我假设您所期望的那样。

4.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object.

Here are most of the built-in objects considered false:

  • constants defined to be false: None and False
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

4.3. Comparisons

Objects of different types, except different numeric types, never compare equal.

...

Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method.

关于python - 理解字符串的真实性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com