best way to replace first word in string?

Fredrik Lundh fredrik at pythonware.com
Thu Oct 20 19:57:41 CEST 2005


Micah Elliott wrote:

> And the regex is comparatively slow, though I'm not confident this one
> is optimally written:
>
>     $ python -mtimeit -s'import re' '
>       re.sub(r"^(\w*)", r"/\1/", "a b c")'
>     10000 loops, best of 3: 44.1 usec per loop

the above has to look the pattern up in the compilation cache for each loop,
and it also has to parse the template string.  precompiling the pattern and
using a callback instead of a template string can speed things up somewhat:

timeit -s"import re; sub = re.compile(r'^(\w*)').sub"
    "sub(lambda x: '/%s/' % x.groups(), 'a b c')"

(but the replace solutions should be faster anyway; it's not free to prepare
for a RE match, and sub uses the same split/join implementation as replace...)

</F>






More information about the Python-list mailing list