> 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) -- http://mail.python.org/mailman/listinfo/python-list