Home > Enterprise >  Remove every comma in string except last one with python
Remove every comma in string except last one with python

Time:04-20

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?

CodePudding user response:

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

CodePudding user response:

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]

  • Related