For循环python多次检查

2024-04-19 17:05:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有如下字符串:

my_string(0) = Your FUTURE looks good.
my_string(1) = your future doesn't look good.

我想打印两行内容如下:

for stings in my_string:
   if 'FUTURE' or 'future' in string:
      print 'Success!'

我的if循环对第一个条件和FUTURE有效,但是第二个条件和future不起作用。原因是什么?你知道吗


Tags: 字符串in内容yourstringifmyfuture
2条回答

您的if语句应理解为

if 'FUTURE':
  if 'future' in string :
    print ...

非空字符串计算为True,因此if 'FUTURE'是冗余的

你想要:

if 'future' in string.lower():
  print ...

用途:

if 'FUTURE' in string or 'future' in string:

或者简单地说:

if 'future' in string.lower()

失败原因:

if 'FUTURE' or 'future' in string:

实际上相当于:

True or ('future' in string)   # bool('FUTURE')  > True

因为第一个条件总是True,所以下一个条件永远不会被检查。事实上,无论字符串包含什么,if条件总是True。你知道吗

在python中,非空字符串总是True,一旦找到真值,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

请注意:

>>> 'FUTURE' in 'FOOFUTURE'
True

is True,as in运算符查找不完全匹配的子字符串。你知道吗

使用regexstr.split处理此类情况。你知道吗

相关问题 更多 >