Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make it shorter (Pythonic)?

Tags:

python

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?

like image 468
Pol Avatar asked Aug 30 '10 13:08

Pol


3 Answers

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.

like image 195
Felix Kling Avatar answered Sep 25 '22 18:09

Felix Kling


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.

like image 21
kriss Avatar answered Sep 24 '22 18:09

kriss


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
like image 39
ondra Avatar answered Sep 25 '22 18:09

ondra