That horrible regexp idiom

Fredrik Lundh fredrik at pythonware.com
Fri Feb 11 13:20:03 EST 2005


Stephen Thorne wrote:

> but it occured to me today, that it is possible to do it in python
> without the extra line.
> '
> '>>> def xsearch(pattern, subject):
> '>>>     yield pattern.search(subject)
>
> '>>> for m in xsearch(foo_pattern, subject):
> '>>>     pass
> '>>> else:
> '>>>     pass
>
> simple, concise, requires no new syntax, and is only a little confusing[1]!

don't forget "untested, and doesn't work unless you add more logic".  here's
a "working" version.

    def xsearch(pattern, subject):
        yield pattern.search(subject)

    for m in xsearch(foo_pattern, subject):
        if m:
            print "match", m
            break
    else:
        print "no match"

which is a rather odd way to write an assignment followed by an if-else.  but
alright, maybe it's an improvement if your "=" key is broken...

(you were joking, right?)

</F> 






More information about the Python-list mailing list