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!

1
  • 2
    I swear a question about this mistake is asked every day Commented Jan 28, 2014 at 13:24

2 Answers 2

29

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Regular expressions could also be used, but you know what they say about regular expressions...
I'd argue that not all(x in s for x in ('AA', 'BB', 'CC')) might be more readable here
@Eric That's fine too, but I prefer mine: return True if any of the string is not in s. :)
@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.
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
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'

3 Comments

The expression he has never tests whether AA or BB are in the string at all.
Yeah you are right, but he still should use an 'and' shouldn't he?
I guess. I also prefer all() or any(), but i'll remove the downvote.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.