best way to replace first word in string?

Steven D'Aprano steve at
Sat Oct 22 05:48:00 CEST 2005

On Thu, 20 Oct 2005 08:26:43 -0700, hagai26 at 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

Efficient for what?

Efficient in disk-space used ("least source code")?

Efficient in RAM used ("smallest objects and compiled code")?

Efficient in execution time ("fastest")?

Efficient in program time ("quickest to write and debug")?

If you use regular expressions, does the time taken in loading the module
count, or can we assume you have already loaded it?

It will also help if you specify your problem a little better. Are you
replacing one word, and then you are done? Or at you repeating hundreds of
millions of times? What is the context of the problem?

Most importantly, have you actually tested your code to see if it is
efficient enough, or are you just wasting your -- and our -- time with
premature optimization?

def replace_word(source, newword):
    """Replace the first word of source with newword."""
    return newword + " " + "".join(source.split(None, 1)[1:])

import time
def test():
    t = time.time()
    for i in range(10000):
        s = replace_word("aa to become", "/aa/")
    print ((time.time() - t)/10000), "s"

py> test()
3.6199092865e-06 s

Is that fast enough for you?


More information about the Python-list mailing list