Replacing large number of substrings

tiissa tiissa at nonfree.fr
Sun Sep 4 12:38:23 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.

You can look at the re.sub [1] and try:

d={'a':'x', 'b':'y'}

def repl(match):
	return d.get(match.group(0), '')

print re.sub("(a|b)", repl, "a b c")



>  >>> dict_replace( "a b c", dict(a="x", b="y") )
> "x y c"

Above, I gave the pattern myself but you can try to have it generated 
from the keys:


def dict_replace(s, d):
     pattern = '(%s)'%'|'.join(d.keys())
     def repl(match):
         return d.get(match.group(0), '')
     return re.sub(pattern, repl, s)


On your example, I get:

 >>> dict_replace('a b c', {'a': 'x', 'b': 'y'})
'x y c'
 >>>



[1] http://python.org/doc/2.4.1/lib/node114.html



More information about the Python-list mailing list