Question about re.sub and callables

Fredrik Lundh fredrik at pythonware.com
Fri Dec 30 04:48:03 EST 2005


"Guyon Morée wrote:

> I can provide re.sub  with a callable, but this will only be called
> with a match object, it's not possible to give it any of the other
> params.
>
> The solution I came up with to tackle this is with some funny globals,
> which doesnt feel 'right':
>
> --------------------------------------------------------------------------------------
> import re
>
> def test(data,pre,post):
>     p = re.compile("([0-9])")
>     global _pre, _post
>     _pre = pre
>     _post = post
>
>     def repl(m):
>         global _pre, _post
>         return _pre + m.group(1) + _post
>
>     print p.sub(repl, data)

contemporary python (nested scopes):

    def test(data,pre,post):
        p = re.compile("([0-9])")
        def repl(m):
            return pre + m.group(1) + post
        print p.sub(repl, data)

old python (object binding):

    def test(data,pre,post):
        p = re.compile("([0-9])")
        def repl(m, pre=pre, post=post):
            return pre + m.group(1) + post
        print p.sub(repl, data)

</F>






More information about the Python-list mailing list