8

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?

Symon
  • 2,170
  • 4
  • 26
  • 34

2 Answers2

16

How about this:

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

I've always found that simple and elegant.

Chris Phillips
  • 11,607
  • 3
  • 34
  • 45
  • Usual Python style doesn't put spaces around parentheses. @Brent had it right, but deleted it for some reason. – Glenn Maynard Mar 18 '11 at 15:27
  • Just what I was looking for, thank you, my code is looking much much better now :) – Symon Mar 18 '11 at 15:46
  • @GlennMaynard: Thanks for the pep-8 reminder. Personally, I find it more legible to have the spaces inside parens, but I should remember to leave them out in examples. – Chris Phillips Mar 18 '11 at 22:21
7

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()
dsmccoy
  • 81
  • 2
  • Now that's more like it. ;-) (Actually you don't need the `!= None` part, BTW.) – martineau Mar 18 '11 at 22:31
  • You're right, it doesn't need the != None. After years of bouncing from one language to another, I have a habit of over specifying. – dsmccoy Mar 19 '11 at 03:01