That horrible regexp idiom
alex23
wuwei23 at gmail.com
Thu Feb 10 03:08:23 EST 2005
Stephen Thorne wrote:
> We've all seen it before. Its a horrible idiom that you would achieve
> in another language by doing:
>
> if (m = foo_pattern.search(subject))
> { }
> else
> { }
>
> but it occured to me today, that it is possible to do it in python
> without the extra line.
>
> '>>> for m in xsearch(foo_pattern, subject):
> '>>> pass
> '>>> else:
> '>>> pass
>
> simple, concise, requires no new syntax, and is only a little
confusing[1]!
It won't have quite the same effect though, as the 'else' statement is
*always* called after the 'for' loop completes.
To have the functionality you're after, you need to include a break in
the code block within the loop.
- alex23
More information about the Python-list
mailing list