Replacing large number of substrings

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Sun Sep 4 18:17:00 EDT 2005


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



More information about the Python-list mailing list