Python multiple comparison style?

I am wondering if there is a way to do the following in a more compact style:

if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"): do_something() 

The problem is that I have more than 4 comparisons in the if statement, and it starts to look pretty long, ambiguous, and ugly. Any ideas?

+8
python comparison coding-style readability
source share
2 answers

How about this:

 if text in ( 'Text1', 'Text2', 'Text3', 'Text4' ): do_something() 

I always found it simple and elegant.

+16
source share

The answer "if text in" is good, but you can also think of a re (regular expression) package if your text strings match the pattern. For example, taking your example literally, β€œText” followed by a number will be a simple regular expression.

Here is an example that should work for β€œText,” followed by a digit. \ Z matches the end of a line, the digit \ d a.

 if re.match('Text\d\Z', text): do_something() 
+7
source share

All Articles