-5

This will probably be a dumb question, but why does this piece of code behave like this?

>>> test = ['aaa','bbb','ccc']
>>> if 'ddd' or 'eee' in test:
...     print True
... 
True
>>> 

I was expecting nothing printed on the stdio, because none of the strings in the IF statement are in the list.

Am I missing something?

4

4 回答 4

7

if 'ddd' or 'eee' in test

被评估为:

if ('ddd') or ('eee' in test)

由于非空字符串始终为True,因此or操作短路并返回True

>>> bool('ddd')
True

要解决这个问题,您可以使用:

if 'ddd' in test or 'eee' in test:

any

if any(x in test for x in ('ddd', 'eee'))

于 2013-10-14T08:04:10.890 回答
4

你的测试应该是

if 'ddd' in test or 'eee' in test:

在您当前拥有的代码中,“ddd”字符串被评估为布尔值,因为它不是空的,所以它的布尔值为 True

于 2013-10-14T08:03:55.703 回答
0
>>> if 'ddd'
...     print True

will print

True

So you should write :

>>> if 'ddd' in test or 'eee' in test:
...     print True

in order to get the result you want.

于 2013-10-14T08:05:37.800 回答
0

你在这里遗漏了一些东西:

if 'ddd' or 'eee' in test:

相当于:

if ('ddd') or ('eee' in test):

因此,这将永远是 True,因为'ddd'它被认为是 True。


你要:

if any(i in test for i in ('ddd', 'eee')):
于 2013-10-14T08:04:45.033 回答