best way to replace first word in string?

Ron Adam rrr at ronadam.com
Sat Oct 22 17:41:58 EDT 2005


Steven D'Aprano wrote:

> 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?


I agree in most cases it's premature optimization.  But little tests 
like this do help in learning to write good performing code in general.

Don't forget a string can be sliced.  In this case testing before you 
leap is a win.   ;-)


import time
def test(func, n):
     t = time.time()
     s = ''
     for i in range(n):
         s = func("aa to become", "/aa/")
     tfunc = t-time.time()
     print func.__name__,':', (tfunc/n), "s"
     print s

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

def replace_word2(source, newword):
     """Replace the first word of source with newword."""
     if ' ' in source:
         return newword + source[source.index(' '):]
     return newword

test(replace_word1, 10000)
test(replace_word2, 10000)


=======
replace_word1 : -3.09998989105e-006 s
/aa/ to become
replace_word2 : -1.60000324249e-006 s
/aa/ to become




More information about the Python-list mailing list