Python 的 "and" 关键字在 len() 函数中是如何解析的?

How is Python's "and" Keyword Parsed in the len() Function?

考虑以下代码:

str1 = "Hi, how are you?"
str2 = "Fine."
str3 = "Goodbye."
print len(str1 and str2 and str3)

最后一行总是打印 len() 的最后一个参数的长度。

为什么会发生这种情况,解释器如何解析该表达式? 在 len() 中使用 and 关键字在句法上如何允许?

真正的问题是 str1 and str2 的计算结果,或者实际上 'a' and 'b' 的计算结果。事实证明 'a' and 'b' 的计算结果为 'b'.

因此在您的示例中,str1 and str2 and str3 的计算结果为 Goodbye.,这解释了为什么 len(str1 and str2 and str3) 是 8。

有趣的是,'a' and 'b''b''a' or 'b''a'

为什么?

我认为这与 Short-circuit evaluation 有关。 由于 bool('a')(或任何非空字符串)为真,Python 解释器需要评估 True and True 或在我们的第二种情况下,True or True.

出于我链接到的维基百科页面中解释的优化原因,在评估 True and True 时,第二个 True 将被返回,但在评估 True or True 时,第一个 True 可以被退回(因为 True or anything 将永远是 True 没有理由去计算第二项)。

为了获得您想要的结果,您应该使用 + 运算符:

str1 = "Hi, how are you?"
str2 = "Fine."
str3 = "Goodbye."
print len(str1 + str2 + str3)