用于循环python多重检查

Max*_*Kim 3 python

如果我有如下字符串:

my_string(0) = Your FUTURE looks good.
my_string(1) = your future doesn't look good.
Run Code Online (Sandbox Code Playgroud)

我想用以下内容打印两行:

for stings in my_string:
   if 'FUTURE' or 'future' in string:
      print 'Success!'
Run Code Online (Sandbox Code Playgroud)

我的if循环适用于第一个条件FUTURE,但是,第二个比较future不起作用.是什么原因?

Ash*_*ary 5

使用:

if 'FUTURE' in string or 'future' in string:
Run Code Online (Sandbox Code Playgroud)

或者干脆:

if 'future' in string.lower()
Run Code Online (Sandbox Code Playgroud)

为什么失败了:

if 'FUTURE' or 'future' in string:
Run Code Online (Sandbox Code Playgroud)

实际上相当于:

True or ('future' in string)   # bool('FUTURE') --> True
Run Code Online (Sandbox Code Playgroud)

因为第一个条件总是为True所以从不检查下一个条件.事实上,无论字符串包含什么条件,if条件总是为True.

一旦找到True值,非空字符串总是True在python中并且or操作短路.

>>> strs1 = "your future doesn't look good."
>>> strs2 = "Your FUTURE looks good."
>>> 'FUTURE' or 'future' in strs1
'FUTURE'
>>> 'Foobar' or 'future' in strs1
'Foobar'
>>> 'Foobar' or 'cat' in strs1
'Foobar'
>>> '' or 'cat' in strs1    #  empty string is a falsey value,
False                       #  so now it checks the  next condition
Run Code Online (Sandbox Code Playgroud)

注意 :

>>> 'FUTURE' in 'FOOFUTURE'
True
Run Code Online (Sandbox Code Playgroud)

True,因为in运算符查找子字符串不是精确的单词匹配.

使用regexstr.split处理此类案件.