Search code examples
pythonstringpython-re

Remove every comma in string except last one with python


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?


Solution

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