best way to replace first word in string?

Micah Elliott mde at micah.elliott.name
Thu Oct 20 13:25:27 EDT 2005


On Oct 20, hagai26 at gmail.com wrote:
> I am looking for the best and efficient way to replace the first word
> in a str, like this:
> "aa to become" -> "/aa/ to become"
> I know I can use spilt and than join them
> but I can also use regular expressions
> and I sure there is a lot ways, but I need realy efficient one

Of course there are many ways to skin this cat; here are some trials.
The timeit module is useful for comparison (and I think I'm using it
correctly :-).  I thought that string concatenation was rather
expensive, so its being faster than %-formatting surprised me a bit:

    $ python -mtimeit '
      res = "/%s/ %s"% tuple("a b c".split(" ", 1))'
    100000 loops, best of 3: 3.87 usec per loop

    $ python -mtimeit '
      b,e = "a b c".split(" ", 1); res = "/"+b+"/ "+e'
    100000 loops, best of 3: 2.78 usec per loop

    $ python -mtimeit '
      "/"+"a b c".replace(" ", "/ ", 1)'
    100000 loops, best of 3: 2.32 usec per loop

    $ python -mtimeit '
      "/%s" % ("a b c".replace(" ", "/ ", 1))'
    100000 loops, best of 3: 2.83 usec per loop

    $ python -mtimeit '
      "a b c".replace("", "/", 1).replace(" ", "/ ", 1)'
    100000 loops, best of 3: 3.51 usec per loop

There are possibly better ways to do this with strings.

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

You'll probably want to experiment with longer strings if a test like
"a b c" is not representative of your typical input.

-- 
_ _     ___
|V|icah |- lliott  http://micah.elliott.name  mde at micah.elliott.name
" "     """



More information about the Python-list mailing list