How best to write this if-else?

Roy Smith roy at panix.com
Sat Apr 21 16:02:46 EDT 2001


I want to test a line to see if it matches any of a bunch of pre-compile 
regexes.  I also want to capture the match objects.  What  really want to 
write is something like this (pseudo-code):

e1 = re.compile ('...')
e2 = re.compile ('...')
e3 = re.compile ('...')

line = file.readline()
if (m = e1.match (line)):
   text = m.group(1)
elif (m = e2.match (line)):
   text = m.group(1)
elif (m = e3.match (line)):
   text = m.group(1)

but I can't write it that way because python doesn't have assignment 
operators.  Seems like I stuck with something like:

m = e1.match(line)
if m:
   text = m.group(1)
else:
   m = e2.match(line)
   if m:
      text = m.group(1)
   else:
     m = e3.match(line)
      if m:
        text = m.group(1)

but the best word I can think to describe that style of coding is "silly".  
Is there really no more straight-forward way to do what I want?



More information about the Python-list mailing list