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?
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.
any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With