Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, "a in b" keyword, how about multiple a's?

Tags:

python

My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:

if "a" in "abrakadabra" :
  print "it is definitely here"

But is it possible to test if more than one item is in the list (any one)? Currently, I'm using the syntax below, but it is kinda long:

if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
  print "found."

Of course regexes can help, but using regexes will take lots of verbose of code and will not be as clear as "a in b". Are there any other Pythonic ways?

like image 983
grigoryvp Avatar asked Apr 18 '09 18:04

grigoryvp


2 Answers

alternatives = ("// @in ", "// @out ", "// @ret ")
if any(a in sTxT for a in alternatives):
    print "found"

if all(a in sTxT for a in alternatives):
   print "found all"

any() and all() takes an iterable and checks if any/all of them evaluate to a true value. Combine that with a generator expressions, and you can check multiple items.

like image 196
Markus Jarderot Avatar answered Sep 20 '22 23:09

Markus Jarderot


any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))

like image 44
Benjamin Peterson Avatar answered Sep 20 '22 23:09

Benjamin Peterson