IF语句(检查列表中的字符串)的行为异常 [英] IF statement (checking for a string in a list) behave weirdly

查看:76
本文介绍了IF语句(检查列表中的字符串)的行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是为什么这段代码的行为如此?

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
>>> 

我期望在stdio上不打印任何内容,因为IF语句中没有任何字符串在列表中.

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

我想念什么吗?

推荐答案

if 'ddd' or 'eee' in test

评估为:

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

因为非空字符串始终为True,所以or操作会短路并返回True.

as a non-empty string is always True, so or operations short-circuits and returns True.

>>> bool('ddd')
True

要解决此问题,您可以使用以下任一方法:

To solve this you can use either:

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

any:

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

这篇关于IF语句(检查列表中的字符串)的行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆