[Tutor] faster substring replacement
Kent Johnson
kent37 at tds.net
Tue Dec 15 22:13:22 CET 2009
On Tue, Dec 15, 2009 at 12:19 PM, Luhmann <luhmann_br at yahoo.com> 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?
>
> Build a regex out of the keys. Provide a function to re.sub() that looks up
the match in the dict and returns the associated value. See
http://code.activestate.com/recipes/81330/
Kent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091215/777b4ba9/attachment.htm>
More information about the Tutor
mailing list