布尔人从字符串中解释出来,出乎意料的行为

时间:2018-03-06 04:50:53

标签: python

任何人都可以在Python(2.7和3)中解释这种行为

>>> a = "Monday" and "tuesday"
>>> a
'tuesday'             # I expected this to be True
>>> a == True
False                 # I expected this to be True
>>> a is True
False                 # I expected this to be True
>>> a = "Monday" or "tuesday"
>>> a
'Monday'              # I expected this to be True
>>> a == True
False                 # I expected this to be True
>>> a is True
False                 # I expected this to be True

我希望因为我使用逻辑运算符andor,所以语句将被评估为a = bool("Monday") and bool("tuesday")

那么这里发生了什么?

1 个答案:

答案 0 :(得分:4)

正如here所解释的,在字符串上使用and / or将产生以下结果:

  • a or b如果a为True则返回a,否则返回b。
  • 如果a为True,则
  • a and b返回b,否则返回。

此行为称为Short-circuit_evaluation,适用于and, orhere

这解释了 1st 案例中的a == 'tuesday' 2nd 'Monday'的原因。

至于检查a == Truea is True,在字符串上使用逻辑运算符会产生一个特定的结果(如上所述),它与bool("some_string")不同。

相关问题