substitution

Iain King iainking at gmail.com
Mon Jan 18 09:23:44 EST 2010


On Jan 18, 2:17 pm, Adi Eyal <a... at digitaltrowel.com> wrote:
> > From: superpollo <ute... 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)

Winner! :)

Iain



More information about the Python-list mailing list