Home > Mobile >  Remove first comma in a string with Python
Remove first comma in a string with Python

Time:04-19

I have this string

s = "1,395,54"

I would like to remove the first comma to obtain the following string:

s = "1395,54"

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

CodePudding user response:

You can use str.replace, it takes a third argument which specifies the number of occurrences to replace.

>>> your_str = "1,395,54"
>>> your_str.replace(",", "", 1)
'1395,54'

CodePudding user response:

By slicing the string. The find method return the index of the first match

s = "1,395,54"

index = s.find(',')
print(s[:index]   s[index 1:])

CodePudding user response:

it is also possible to count every comma in str and remove every but last using:

str = "144,543,539,554"
str = str.replace(",", "", (str.count(',')-1))
# Output:
# 144543539,554

Hope I helped.

  • Related