==和比较的逻辑是什么?

sud*_*nce 1 python logic boolean python-3.x

所以我在寻找问题并遇到了这个最近的问题

答案很简单,但我注意到的一件事是它实际上确实返回了SPAM精确匹配

所以这段代码

text = 'buy now'

print(text == 'buy now' in text)  # True
Run Code Online (Sandbox Code Playgroud)

返回True,我不明白为什么

我试图通过将括号放在不同的地方来找出答案

text = 'buy now'

print(text == ('buy now' in text))  # False
Run Code Online (Sandbox Code Playgroud)

返回False

text = 'buy now'

print((text == 'buy now') in text) # TypeError
Run Code Online (Sandbox Code Playgroud)

提高TypeError: 'in <string>' requires string as left operand, not bool

我的问题是这里发生了什么以及为什么会这样?

聚苯乙烯

我在 Ubuntu 20.04 上运行 Python 3.8.10

che*_*ner 5

==in被视为比较运算符,因此该表达式text == 'buy now' in text受比较链的约束,使其等效于

text == 'buy now' and 'buy now' in text
Run Code Online (Sandbox Code Playgroud)

两者都是andare的操作数True,因此是True结果。

添加括号时,您要么检查 if text == True(这是False),要么检查 if True in text(这是TypeError;str.__contains__不接受布尔参数)。