substitution

Duncan Booth duncan.booth at invalid.invalid
Mon Jan 18 11:20:46 EST 2010


Adi Eyal <adi at digitaltrowel.com> wrote:

> Using regular expressions the answer is short (and sweet)
> 
> mapping = {
>         "foo" : "bar",
>         "baz" : "quux",
>         "quuux" : "foo"
> }
> 
> pattern = "(%s)" % "|".join(mapping.keys())
> repl = lambda x : mapping.get(x.group(1), x.group(1))
> s = "fooxxxbazyyyquuux"
> re.subn(pattern, repl, s)

I'd use a def as being IMHO clearer than the lambda but YMMV. More 
importantly I'd also escape the keys in case they contain any characters 
special to regular expressions:

>>> mapping = {
        "foo" : "bar",
        "baz" : "quux",
        "quuux" : "foo"
}
>>> import re
>>> pattern = "(%s)" % "|".join(re.escape(k) for k in mapping)
>>> def repl(x): return mapping[x.group(1)]

>>> s = "fooxxxbazyyyquuux"
>>> re.subn(pattern, repl, s)
('barxxxquuxyyyfoo', 3)
>>> re.sub(pattern, repl, s)
'barxxxquuxyyyfoo'
>>> 


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list