In article <431af96c$0$29438$da0feed9 at news.zen.co.uk>, Will McGugan <news at NOwillmcguganSPAM.com> 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4