substitution

Peter Otten __peter__ at web.de
Mon Jan 18 05:45:37 EST 2010


superpollo wrote:

> superpollo ha scritto:
>> hi.
>> 
>> what is the most pythonic way to substitute substrings?
>> 
>> eg: i want to apply:
>> 
>> foo --> bar
>> baz --> quux
>> quuux --> foo
>> 
>> so that:
>> 
>> fooxxxbazyyyquuux --> barxxxquuxyyyfoo
>> 
>> bye
> 
> i explain better:
> 
> say the subs are:
> 
> quuux --> foo
> foo --> bar
> baz --> quux
> 
> then i cannot apply the subs in sequence (say, .replace() in a loop),
> otherwise:
> 
> fooxxxbazyyyquuux --> fooxxxbazyyyfoo --> barxxxbazyyybar -->
> barxxxquuxyyybar
> 
> not as intended...

If you want to avoid regular expressions:

def replace_many(s, pairs):
    if len(pairs):
        a, b = pairs[0]
        rest = pairs[1:]
        return b.join(replace_many(t, rest) for t in s.split(a))
    else:
        return s

assert replace_many("abc", ["ab", "bc", "ca"]) == "bca"
assert (replace_many("fooxxxbazyyyquuux",
                     [("quuux", "foo"), ("foo", "bar"), ("baz", "quux")])
        == "barxxxquuxyyyfoo")

Not tested.

Peter



More information about the Python-list mailing list