Double replace or single re.sub?
Alex Martelli
aleaxit at yahoo.com
Fri Oct 28 00:34:26 EDT 2005
Iain King <iainking at gmail.com> 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)
>
> Would this be a quicker/better way of doing it?
*MEASURE*!
Helen:~/Desktop alex$ python -m timeit -s'import re; h="<i>aap</i>"' \
> 'h.replace("<i>", "<em>").replace("</i>", "</em>")'
100000 loops, best of 3: 4.41 usec per loop
Helen:~/Desktop alex$ python -m timeit -s'import re; h="<i>aap</i>"' \>
're.sub("<([/]*)i>", r"<\1em>}", h)'
10000 loops, best of 3: 52.9 usec per loop
Helen:~/Desktop alex$
timeit.py is your friend, remember this...!
Alex
More information about the Python-list
mailing list