Replacing large number of substrings

Robert Kern rkern at ucsd.edu
Sun Sep 4 12:52:50 EDT 2005


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
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list