On Jan 18, 2:17 pm, Adi Eyal <a...@digitaltrowel.com> wrote: > > From: superpollo <ute...@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 -- http://mail.python.org/mailman/listinfo/python-list