Question about re.sub and callables

skip at pobox.com skip at pobox.com
Fri Dec 30 00:26:47 EST 2005


    Guyon> The solution I came up with to tackle this is with some funny
    Guyon> globals, which doesnt feel 'right':

    ...

    Guyon> Is there any other way to do this?

You've almost got it right.  Just lose the "global":

    def test(data, pre, post):
        p = re.compile("([0-9])")

        def repl(m):
            return pre + m.group(1) + post

        print p.sub(repl, data)

For a full explanation, google for "python nested scopes".

Skip



More information about the Python-list mailing list