Double replace or single re.sub?

Josef Meile jmeile at
Wed Oct 26 21:42:32 CEST 2005

Hi Iain,

 > Would this be a quicker/better way of doing it?
I don't know if this is faster, but it is for sure more elegant:

I really like it because of its simplicity an easy use. (Thanks to
Fredrik Lundh for the script). However, I suggested it once to replace
the approach you suggested in a web application we have, but it was
rejected because the person, who benchmarked it, said that it was OK for
small strings, but for larger ones performance were an issue. Anyway,
for my own applications, performance isn't an issue, so, I use it some

By the way, the benchmarking, from which I don't have any information,
was done in python 2.1.3, so, for sure you will get a better performance
with 2.4.


Iain King wrote:
> I have some code that converts html into xhtml.  For example, convert
> all <i> tags into <em>.  Right now I need to do to string.replace calls
> for every tag:
> html = html.replace('<i>','<em>')
> html = html.replace('</i>','</em>')
> I can change this to a single call to re.sub:
> html = re.sub('<([/]*)i>', r'<\1em>', html)

> Iain

More information about the Python-list mailing list