Will McGugan 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"
(n.b. untested!) def dict_replace(string, replacements): for key, value in replacements.iteritems(): string = string.replace(key, value) return string How well this works depends on how large is "large." If "large" is really very large, then you might want to build something using a more suitable algorithm like the Aho-Corasick algorithm. http://www.lehuen.com/nicolas/download/pytst/ http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list