substitution

Adi Eyal adi at digitaltrowel.com
Mon Jan 18 09:17:56 EST 2010


> From: superpollo <utente at esempio.net>
> To:
> Date: Mon, 18 Jan 2010 11:15:37 +0100
> Subject: substitution
> 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


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)



More information about the Python-list mailing list