Question about re.sub and callables

Guyon Morée guyon.moree at gmail.com
Fri Dec 30 06:07:14 CET 2005


I have a function with some params including some data to be used with
re.sub and some other data which i want to use in the replacement.

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)

>>> test("number 1 test", "->", "<-")
number ->1<- test
--------------------------------------------------------------------------------------

Is there any other way to do this?

cheers,

Guyon Morée
http://gumuz.looze.net/




More information about the Python-list mailing list