C-like assignment expression?
Ulrich Eckhardt
eckhardt at satorlaser.com
Wed May 21 06:14:22 EDT 2008
boblatest at googlemail.com wrote:
> I have an if-elif chain in which I'd like to match a string against
> several regular expressions. Also I'd like to use the match groups
> within the respective elif... block. The C-like idiom that I would
> like to use is this:
>
> if (match = my_re1.match(line):
> # use match
> elsif (match = my_re2.match(line)):
> # use match
> elsif (match = my_re3.match(line))
> # use match
>
> ...buy this is illegal in python. The other way is to open up an else:
> block in each level, do the assignment and then the test. This
> unneccessarily leads to deeper and deeper nesting levels which I find
> ugly.
How about this (untested) code:
for re in (re1, re2, re3):
match = re.match(line)
if match:
# use it
This requires that "use it" means the same for each regular expression
though...
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
More information about the Python-list
mailing list