In article <[EMAIL PROTECTED]>, Will McGugan <[EMAIL PROTECTED]> wrote:
> Hi, > > Is there a simple way of replacing a large number of substrings in a > string? I was hoping that str.replace could take a dictionary and use it > to replace the occurrences of the keys with the dict values, but that > doesnt seem to be the case. > > To clarify, something along these lines.. > > >>> dict_replace( "a b c", dict(a="x", b="y") ) > "x y c" Hi, Will, Perhaps the following solution might appeal to you: . import re . . def replace_many(s, r): . """Replace substrings of s. The parameter r is a dictionary in . which each key is a substring of s to be replaced and the . corresponding value is the string to replace it with. . """ . exp = re.compile('|'.join(re.escape(x) for x in r.keys())) . return exp.sub(lambda m: r.get(m.group()), s) Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA -- http://mail.python.org/mailman/listinfo/python-list