7

Similar to here: Does Python have a string contains substring method? This question only deals with one substring within a string, I want to test one of several.

Something like:

if 'AA' or 'BB' or 'CC' not in string:
    print 'Nope'

However, if my test string is:

string='blahblahAA'

the if still evaluates to True and prints the statement. I'm probably just understanding the syntax incorrectly, any help would be appreciated.

Thanks!

Community
  • 1
  • 1
pgierz
  • 674
  • 3
  • 7
  • 14

2 Answers2

28

Use any for this:

>>> s = 'blahblahAA'
>>> any(x not in s for x in ('AA', 'BB', 'CC'))
True

Your current code is equivalent to:

if ('AA') or ('BB') or ('CC' not in string)

As 'AA' is True(bool('AA') is True), so this always evaluates to True.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Regular expressions could also be used, but you know what they say about regular expressions... – JAB Jan 28 '14 at 13:25
  • 2
    I'd argue that `not all(x in s for x in ('AA', 'BB', 'CC'))` might be more readable here – Eric Jan 28 '14 at 13:25
  • @Eric That's fine too, but I prefer mine: *return `True` if any of the string is not in `s`.* :) – Ashwini Chaudhary Jan 28 '14 at 13:31
  • 2
    @Eric Until somebody who doesn't know that `(!A || !B) == !(A && B)` looks at the code and goes "huh"? (While I would hope that most programmers are aware of that property of Boolean algebra, there's always the possibility of one that doesn't.) I do prefer Ashwini's version, personally, but that's just a matter of taste; if the question were asking for none of the substrings to be present, I'd probably use `not any(x in s for x in ('AA', 'BB', 'CC'))`, though `all(x not in s for x in ('AA', 'BB', 'CC'))` would work as well. – JAB Jan 28 '14 at 13:33
  • This is what I meant: if the question were asking for none of the substrings to be present, I'd probably use not any(x in s for x in ('AA', 'BB', 'CC')), and solved the problem. Thanks – pgierz Jan 28 '14 at 13:42
0

You should use an and instead of an or statement. Right now, you always print 'Nope' if one of the substrings is not in your string.

In the example given above, you still print 'Nope' because 'BB' and 'CC' are not in the string and the whole expression evaluates to true.

Your code could look like this:

if ('AA' not in string) and ('BB' not in string) and ('CC' not in string):
    print 'Nope'
fedorSmirnov
  • 701
  • 3
  • 9
  • 19