Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple comparisons 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 i have more than just 4 comparisons in the if statement and it's starting to look rather long, ambiguous, and ugly. Any ideas?

like image 869
Symon Avatar asked Mar 18 '11 15:03

Symon


2 Answers

How about this:

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

I've always found that simple and elegant.

like image 171
Chris Phillips Avatar answered Nov 01 '22 10:11

Chris Phillips


The "if text in" answer is good, but you might also think about the re (regular expressions) package if your text strings fit a pattern. For example, taking your example literally, "Text" followed by a digit would be a simple regular expression.

Here's an example that should work for "Text" followed by a digit. the \Z matches the end of the string, the \d a digit.

if re.match('Text\d\Z', text):
   do_something()
like image 22
dsmccoy Avatar answered Nov 01 '22 10:11

dsmccoy