tags:

views:

275

answers:

5

I have to check a lot of worlds if they are in string... code looks like:

if "string_1" in var_string or "string_2" in var_string or "string_3" in var_string or "string_n" in var_string:
    do_something()

how to make it more readable and more clear?

+31  A: 

This is one way:

words = ['string_1', 'string_2', ...]

if any(word in var_string for word in words):
    do_something();

Reference: any()

Update:

For completeness, if you want to execute the function only if all words are contained in the string, you can use all() instead of any().

Also note that this construct won't do any unnecessary computations as any will return if it encounters a true value and a generator expression is used to create the Boolean values. So you also have some kind of short-circuit evaluation that is normally used when evaluating Boolean expressions.

Felix Kling
Thanks that's what i was needed...
Pol
@Pol: You should mark this as accepted, then.
Paolo Bergantino
+1  A: 

Have you looked at filter?

filter( lambda x: x in var_string, ["myString", "nextString"])

which then can be combined with map to get this

map( doSomething(), filter(lambda x: x in var_string, ["myString", "nextString"] ) )

EDIT:

of course that doesn't do what you want. Go with the any solution. For some reason I thought you wanted it done every time instead of just once.

wheaties
Won't that execute `doSomething()` for any word that is in the string?
Felix Kling
Yes. Oh wait, he only wanted is done once, no? Crap. Thanks for pointing that out.
wheaties
+1  A: 
>>> import re
>>> string="word1testword2andword3last"
>>> c=re.compile("word1|word2|word3")
>>> c.search(string)
<_sre.SRE_Match object at 0xb7715d40>
>>> string="blahblah"
>>> c.search(string)
>>>
ghostdog74
this appears less concise and less pythonic to my python eyes
marr75
Define Pythonic? What makes something Pythonic? The only concise statement above is re.compile and re.search. The rest are just showing output examples. Oh wait, the Python interpreter prompt might be blurring your Pythonic eyes...
ghostdog74
+2  A: 
import re
if re.search("string_1|string_2|string_n", var_strings): print True

The beauty of python regex it that it returns either a regex object (that gives informations on what matched) or None, that can be used as a "false" value in a test.

kriss
+2  A: 

With regex that would be:

import re
words = ['string_1', 'string_2', ...]

if re.search('|'.join([re.escape(w) for w in words]), var_string):
    blahblah
ondra
I nearly to upvoted because it's inventive and Felix Kling already got so many upvotes ;) But it fails if any of the strings contains regex metacharacters.
delnan
And that's why there is the re.escape....
ondra