best version: gnibbler's answer
Since you need speed (millions of times is a lot), I profiled. This one is about twice as fast as splitting the list:
i = 0
while 1:
if mystr[i] == ',': break
i += 1
mystr = mystr[i+1:] + ', ' + latest_value
It assumes that there is one space after each comma. If that's a problem, you can use:
i = 0
while 1:
if mystr[i] == ',': break
i += 1
mystr = mystr[i+1:].strip() + ', ' + latest_value
which is only slightly slower than the original but much more robust. It's really up to you to decide how much speed you need to squeeze out of it. They both assume that there will be a comma in the string and will raise an IndexError
if one fails to appear. The safe version is:
i = 0
while 1:
try:
if mystr[i] == ',': break
except IndexError:
i = -1
break
i += 1
mystr = mystr[i+1:].strip() + ', ' + latest_value
Again, this is still significantly faster than than splitting the string but does add robustness at the cost of speed.
Here's the timeit results. You can see that the fourth method is noticeably faster than the third (most robust) method, but slightly slower than the first two methods. It's the fastest of the two robust solutions though so unless you are sure that your strings will have commas in them (i.e. it would already be considered an error if they didn't) then I would use it anyway.
$ python -mtimeit -s'from strings import tests, method1' 'method1(tests[0], "10")'
1000000 loops, best of 3: 1.34 usec per loop
$ python -mtimeit -s'from strings import tests, method2' 'method2(tests[0], "10")'
1000000 loops, best of 3: 1.34 usec per loop
$ python -mtimeit -s'from strings import tests, method3' 'method3(tests[0], "10")'
1000000 loops, best of 3: 1.5 usec per loop
$ python -mtimeit -s'from strings import tests, method4' 'method4(tests[0], "10")'
1000000 loops, best of 3: 1.38 usec per loop
$ python -mtimeit -s'from strings import tests, method5' 'method5(tests[0], "10")'
100000 loops, best of 3: 1.18 usec per loop
This is gnibbler's answer