[Tutor] faster substring replacement
Tim Golden
mail at timgolden.me.uk
Tue Dec 15 21:25:57 CET 2009
Luhmann wrote:
> 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?
You're basically moving slowly towards a templating mechanism.
Depends on just how fancy you want to get. In short, to
do this kind of thing, the steps are:
1) Roll-your-own dict solution [what you've done]
2) Use re.sub with/without callbacks
3) Use an existing templating solution (of which there are many in the Python world).
Exactly how far down that line you go depends on the complexity and
need for speed. But I'm surprised that the dictionary solution is that slow.
Especially since the code you quote above only actually makes one
replacement before it returns the altered string :)
(You could probably squeeze a tiny bit more juice out of it my
iterating over the dict items rather than they keys:
for old, new in evildict.items ():
text = text.replace (old, new)
)
TJG
More information about the Tutor
mailing list