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
和==
都in
被视为比较运算符,因此该表达式text == 'buy now' in text
受比较链的约束,使其等效于
text == 'buy now' and 'buy now' in text
Run Code Online (Sandbox Code Playgroud)
两者都是and
are的操作数True
,因此是True
结果。
添加括号时,您要么检查 if text == True
(这是False
),要么检查 if True in text
(这是TypeError
;str.__contains__
不接受布尔参数)。
归档时间: |
|
查看次数: |
36 次 |
最近记录: |