Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have a cleaner way to express "if x contains a|b|c|d..."? [duplicate]

The Pythonic way to check if a string x is a substring of y is:

if x in y: 

Finding if x is equivalent to a, b, c, d, e, f or g is also Pythonic:

if x in [a,b,c,d,e,f,g]: 

But checking if some string x contains either a, b, c, d, e, f or g seems clunky:

if a in x or b in x or c in x or d in x or e in x or f in x or g in x 

Is there a more Pythonic method of checking if a string x contains an element of a list?

I know it is trivial to write this myself using a loop or using a regex:

re.search('(dog|cat|bird|mouse|elephant|pig|cow)', x) 

but I was wondering if there was a cleaner way that does not involve regex.

like image 543
tom Avatar asked Oct 31 '13 18:10

tom


People also ask

How do you check if a string contains a word in Python?

The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example: sentence = 'There are more trees on Earth than stars in the Milky Way galaxy' word = 'galaxy' if word in sentence: print('Word found.

How do you find if a string contains a substring in Python?

The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")


2 Answers

The Pythonic approach would be to use any():

if any(s in x for s in (a,b,c,d,e,f,g)): 

From the linked documentation:

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):     for element in iterable:         if element:             return True     return False 

Also, notice that I've used a tuple instead of a list here. If your a-g values are pre-defined, then a tuple would indeed be preferred. See: Are tuples more efficient than lists in Python?

like image 104
arshajii Avatar answered Sep 18 '22 10:09

arshajii


if any(q in x for q in [a,b,c,d,e,f,g]): 

I think that's about as short & Pythonic as you can get it.

like image 43
jwodder Avatar answered Sep 21 '22 10:09

jwodder