Remove every comma in string except last one with python

Viewed 165

I have those strings

s1 = "1,395,54"
s2 = "1,5,6,75"

I would like all commas except the last to obtain the following strings:

s1 = "1395,54"
s2 = "156,75"

What is the most efficient way to solve this simple problem?

3 Answers

Here is the solution with str.replace. replace function accepts a third argument which specifies Maximum number of occurrences to replace. So you can pass a number which is one less than the number of occurrences of , in your string(your_string.count(",") - 1).

>>> s1 = "1,395,54"
>>> s1.replace(",", "", s1.count(",") - 1)
'1395,54'
>>> s2 = "1,5,6,75"
>>> s2.replace(",", "", s2.count(",") - 1)
'156,75'

You could split and rejoin with f-strings -

*rest, last = s1.split(',')
f'{"".join(rest)},{last}'

You can combine those into a one liner -

''.join(s1.split(',')[:-1]) + "," + s1.split(',')[-1]

You might also use a pattern asserting that there is a comma present to the right with only digits in between:

import re

s1 = "1,395,54"
s2 = "1,5,6,75"

pattern = r",(?=\d*,)"

print(re.sub(pattern, "", s1))  # 1395,54
print(re.sub(pattern, "", s2))  # 156,75

The broader variant accepting any char except a comma inbetween:

,(?=[^,]*,)
Related