affectation in if statement

Gary Herron gherron at islandtraining.com
Tue Mar 16 04:10:39 EDT 2010


samb wrote:
> Hi,
>
> I'm trying to do something like :
>
> if m = re.match(r'define\s+(\S+)\s*{$', line):
>     thing = m.group(1)
> elif m = re.match(r'include\s+(\S+)$', line):
>     thing = m.group(1)
> else
>     thing = ""
>
> But in fact I'm not allowed to affect a variable in "if" statement.
> My code should then look like :
>
> if re.match(r'define\s+(\S+)\s*{$', line):
>     m = re.match(r'define\s+(\S+)\s*{$', line)
>     thing = m.group(1)
> elif re.match(r'include\s+(\S+)$', line):
>     m = re.match(r'include\s+(\S+)$', line)
>     thing = m.group(1)
> else
>     thing = ""
>
> Which is not nice because I'm doing twice the same instruction
> or like :
>
> m = re.match(r'define\s+(\S+)\s*{$', line)
> if m:
>     thing = m.group(1)
> else:
>     m = re.match(r'include\s+(\S+)$', line)
>     if m:
>         thing = m.group(1)
>     else
>         thing = ""
>
> Which isn't nice neither because I'm going to have maybe 20 match
> tests and I wouldn't like to have 20 indentations.
>
> Anyone a recommendation?
>   

Yes:  Use an array of regular expressions and a loop (untested):

exprs = ["...",
              "...",
              ]

thing = ""
for expr in exps:
      m = re.match(expr, line)
      if m:
         thing = m.group(1)
         break

> Thanks!
>   

Gary Herron




More information about the Python-list mailing list