Does Python have a cleaner way to express "if x contains a|b|c|d..."?
The Pythonic way to check if a string
x is a substring of
if x in y:
x is equivalent to
g is also Pythonic:
if x in [a,b,c,d,e,f,g]:
But checking if some string
x contains either
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:
but I was wondering if there was a cleaner way that does not involve regex.
The Pythonic approach would be to use
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
g values are pre-defined, then a tuple would indeed be preferred. See: Are tuples more efficient than lists in Python?
★ Back to homepage or read more recommendations: