如果(字符串或字符串或字符串)不在变量
问题描述:
我试图让if
语句正常工作,但由于某些原因,它不起作用。它应该非常简单。如果(字符串或字符串或字符串)不在变量
假设字符串title = "Today I went to the sea"
我的代码是:
if "Today" or "sea" in title:
print 1
if "Today" or "sea" not in title:
print 1
两个规范导致1
答
更改您的代码如下:
if "Today" in title or "sea" in title:
print 1
(类似的第二段代码)。
if
陈述的工作原理是他们评估加入词的表达式,如or
或and
。所以,你的语句读这样的:
if ("Today") or ("sea" in title):
print 1
因为"Today"
是truthy它一直在评估对true
答
我保证这已经回答了其他地方的SO,你应该先问了一个新问题前检查有。
与您的代码的问题:
if 'Today' or 'sea' in title:
此检查“今天”是真,或者“海”为标题,“今天” ==类型(字符串),因此它的存在/诚然,“海'在标题==真和评估为真,if 'today' or 'sea' not in title
'今天'又是类型(字符串),因此存在/ True和'海'不是在标题=假,并再次评估为真。如何解决这个问题! if 'Today' in title or 'Sea' in title:
或更低版本,使其易于修改!祝你好运!
strings_to_compare = ['Today', 'sea', 'etc...']
for i in strings_to_compare:
if i in title:
print i
为什么要投票? – winhowes