Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If string contains one of several substrings Python [duplicate]

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!

like image 267
pgierz Avatar asked Jul 09 '26 16:07

pgierz


1 Answers

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.

like image 141
Ashwini Chaudhary Avatar answered Jul 12 '26 05:07

Ashwini Chaudhary