user15887962
user15887962

Reputation:

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?

Upvotes: 1

Views: 548

Answers (3)

user459872
user459872

Reputation: 24602

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'

Upvotes: 4

The fourth bird
The fourth bird

Reputation: 163362

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:

,(?=[^,]*,)

Upvotes: 1

Mortz
Mortz

Reputation: 4879

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]

Upvotes: 1

Related Questions