How to Remove Commas from String in Python?

Spread the love

Problem –

You want to remove commas from string in python.

Solution –

To remove commas from a string in python we can use the replace method or re package.

Using replace method –

The replace() method replace each matching characters from a string with a new characters.

Syntax –

string.replace(old, new, [, count])

old – old substring you want to replace

new – new substring with which you want to replace

count (optional) – the number of times you want to replace the old substring with the new one.

Example –

In [1]: string = "Apple, Orange, Mango"

In [2]: string.replace(",", "")
Out[2]: 'Apple Orange Mango'

Here we replaced all commas with “” . If you want to replace only the first comma then you can use the count parameter.

In [3]: string.replace(",", "", 1)
Out[3]: 'Apple Orange, Mango'

Here the value of count is set to 1 so it only replaced the first comma.

Using re package –

You can also use the re package to remove commas from a string in python.

In [5]: import re

In [6]: string = "Apple, Orange, Mango"

In [7]: re.sub(",", "", string)
Out[7]: 'Apple Orange Mango'

To learn more about re.sub() method read this article – Python Regular Expression – re.sub() – search and replace string

Rating: 1 out of 5.

Leave a Reply