[Tutor] faster substring replacement

R. Alan Monroe amonroe at columbus.rr.com
Wed Dec 16 04:02:04 CET 2009


> Hi folks,

> I'm trying to do something like this:

>>>> evildict= {'good' : 'bad' , 'love' : 'hate' , 'God': 'Satan'}

>>>> def make_evil(text)
> ...        for a in evildict:
> ...              text=text.replace(a, evildict[a])
> ...              return text
>     

> This works fine, but it soon gets too slow as the size of text and dictionary begin to grow.
> Can you guys suggest me a way to make it faster?

Would it help to do it in linear fashion? Reading the source text one
word at a time, doing a dict check for that word, then flushing that
word to output?

I'm wondering whether text.replace has to shove oodles of text to the
right in memory when you replace a shorter word with a longer word.
Someone else on the list may know.

Alan



More information about the Tutor mailing list