1

I have a python string like this;

input_str = "2548,0.8987,0.8987,0.1548"

I want to remove the sub-string at the end after the last comma, including the comma itself.

The output string should look like this;

output_str = "2548,0.8987,0.8987"

I am using python v3.6

3
  • What if there was no comma and only one item... would you keep that or not? Commented Sep 28, 2017 at 9:23
  • @Jon Clements, The string I have in mind will always have more than 1 item. Commented Sep 28, 2017 at 9:41
  • Famous last words :) Commented Sep 28, 2017 at 9:41

5 Answers 5

7

With split and join

','.join(input_str.split(',')[:-1])

Explanation

# Split string by the commas
>>> input_str.split(',')
['2548', '0.8987', '0.8987', '0.1548']

# Take all but last part
>>> input_str.split(',')[:-1]
['2548', '0.8987', '0.8987']

# Join the parts with commas
>>> ','.join(input_str.split(',')[:-1])
'2548,0.8987,0.8987'

With rsplit

input_str.rsplit(',', maxsplit=1)[0]

With re

re.sub(r',[^,]*$', '', input_str)

If you are gonna to use it multiple times make sure to compile the regex:

LAST_ELEMENT_REGEX = re.compile(r',[^,]*$')
LAST_ELEMENT_REGEX.sub('', input_str)
Sign up to request clarification or add additional context in comments.

4 Comments

Brilliant. I tested that it works! Now, I am trying to decode what your one-liner does. Seems like there's quite a few operations in that single line.
Check the other ways, the rsplit is the cleanest in my opinion.
@PacoH. use .rpartition - it's optimised for a split case of 0 or 1...
@Paco H, rsplit is the simplest solution. I can understand it. Thanks.
1

You can try this simplest one. Here we are using split, pop and join to achieve desired result.

Try this code snippet here

input_str = "2548,0.8987,0.8987,0.1548"
list= input_str.split(",") #Split string over ,
list.pop() #pop last element
print(",".join(list)) #joining list again over ,

Comments

1

Assuming that there is definitely a comma in your string:

output_str = input_str[:input_str.rindex(',')]

That is "Take everything from the start of the string up to the last index of a comma".

Comments

1

There's the split function for python :

print input_str.split(',')

Will return :

['2548,0.8987,0.8987', '0.1548']

But in case you have multiple commas, rsplit is here for that :

str = '123,456,789'
print str.rsplit(',', 1)

Will return :

['123,456','789']

2 Comments

No, it won't return that. split(',') will split on every comma, not just the last one.
In this case there's rsplit, I updated my answer
0

Here you go

sep = ','
count = input_str.count(sep)
int i=0;
output = ''
while(i<count):
    output += input_str.split(sep, 1)[i]
    i++
input_str = output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.