类似于这里:Python有字符串包含子字符串的方法吗? 这个问题只涉及一个字符串中的一个子字符串,我想测试其中的几个。
类似于下面的代码:
if 'AA' or 'BB' or 'CC' not in string:
print 'Nope'
然而,如果我的测试字符串是:
string='blahblahAA'
如果条件语句仍然为True,则打印该语句。我可能只是对语法理解有误,希望得到帮助。
谢谢!
类似于这里:Python有字符串包含子字符串的方法吗? 这个问题只涉及一个字符串中的一个子字符串,我想测试其中的几个。
类似于下面的代码:
if 'AA' or 'BB' or 'CC' not in string:
print 'Nope'
string='blahblahAA'
如果条件语句仍然为True,则打印该语句。我可能只是对语法理解有误,希望得到帮助。
谢谢!
使用any
来实现:
>>> s = 'blahblahAA'
>>> any(x not in s for x in ('AA', 'BB', 'CC'))
True
您当前的代码等同于:
if ('AA') or ('BB') or ('CC' not in string)
由于'AA'
为True
(bool('AA')
为True
),因此这总是评估为True
。
not all(x in s for x in ('AA', 'BB', 'CC'))
可能更易读。 - Erics
中,则返回True
。 :) - Ashwini Chaudhary(!A || !B) == !(A && B)
的布尔代数属性(虽然我希望大多数程序员都知道这个属性,但总有可能有一个不知道的)。就我个人而言,我更喜欢Ashwini的版本,但这只是品味问题;如果问题要求没有任何子字符串存在,我可能会使用not any(x in s for x in ('AA', 'BB', 'CC'))
,尽管all(x not in s for x in ('AA', 'BB', 'CC'))
也可以。 - JAB你应该使用“and”而不是“or”语句。现在,如果一个子字符串不在你的字符串中,你总是打印“Nope”。
在上面给出的例子中,你仍然打印“Nope”,因为“BB”和“CC”不在字符串中,整个表达式求值为true。
你的代码可以像这样:
if ('AA' not in string) and ('BB' not in string) and ('CC' not in string):
print 'Nope'