Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python?

In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'

I need to add a new value onto the end and remove the first value,

e.g. '5,22,7,814,3,4' -> '22,7,814,3,4,1'

Currently, I do this as follows:

mystr = '5,22,7,814,3,4'
latestValue='1'
mylist = mystr.split(',')
mystr = ''
for i in range(len(mylist)-1):
   if i==0:
      mystr += mylist[i+1]
   if i>0:
      mystr += ','+mylist[i+1]

mystr += ','+latestValue

This runs millions of times in my code and I've identified it as a bottleneck, so I'm keen to optimize it to make it run faster.

What is the most efficient to do this (in terms of runtime)?

like image 739
Pete W Avatar asked Nov 06 '10 03:11

Pete W


People also ask

What is the most efficient way to concatenate strings in Python?

Concatenate Strings using the Join As shown above, using the + operator is more efficient. It takes less time for execution.

What is the most efficient way to concatenate many strings together?

Concatenate multiple strings The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator. However, there's another method that allows an easy way of concatenating multiple strings. It is using the in-place (+=) operator.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

Are F strings faster than concatenation?

Summary: Using the string concatenation operator is slightly faster than using format string literals. Unless you are performing many hundreds of thousands of string concatenations and need them done very quickly, the implementation chosen is unlikely to make a difference.


2 Answers

Use this:

if mystr == '':
    mystr = latestValue
else:
    mystr = mystr[mystr.find(",")+1:] + "," + latestValue

This should be much faster than any solution which splits the list. It only finds the first occurrence of , and "removes" the beginning of the string. Also, if the list is empty, then mystr will be just latestValue (insignificant overhead added by this) -- thanks Paulo Scardine for pointing that out.

like image 158
Gabi Purcaru Avatar answered Nov 15 '22 07:11

Gabi Purcaru


_, sep, rest = mystr.partition(",")
mystr = rest + sep + latestValue

It also works without any changes if mystr is empty or a single item (without comma after it) due to str.partition returns empty sep if there is no sep in mystr.

You could use mystr.rstrip(",") before calling partition() if there might be a trailing comma in the mystr.

like image 22
jfs Avatar answered Nov 15 '22 07:11

jfs