Python program to remove commas from a string

Different ways in Python to remove commas from a string:

This is one common problem that we face in development world in any programming language. For example, we have one string hello,world and we need to remove all commas from this string to create the new string helloworld. Or, if we are receiving one number as 10,20,3 and we want to remove all commas and store it as 10203, these methods will come in handy.

In python, we can do this in different ways. We can use the replace method that is already provided in the string class of Python. Or we can use regex or regular expression.

Example 1: Remove all commas using replace:

replace method is defined in string class of Python. This is defined as:

string.replace(o, n, count)

It will replace the substring o with the new substring n for count number of times. count is optional and if we don’t provide its value, it will replace all substrings found with the new substring.

In our case, o is , and n is an empty string, and we don’t have to provide count.

Since string is immutable, it creates one new string and returns that.

Let’s try it with an example:

given_string = input('Enter a string: ')
new_string = given_string.replace(',', '')

print('New string: {}'.format(new_string))

Here,

  • We are taking the string as input from the user.
  • The user input string is stored in given_string.
  • new_string is created by replacing all commas with empty string.
  • The last line is printing the new string.

If you run this program, it will print output as like below:

Enter a string: hello,world
New string: helloworld

Enter a string: 1,2,3,4,5
New string: 12345

Enter a string: 12345
New string: 12345

Example 2: Remove all commas using regular expression:

Regular expressions or regex is another way to remove commas from a string in Python. Python provides one module called re that can be used to remove all commas from a string.

re module has one method called sub which is defined as below:

re.sub(p, replace, str, count = 0)

Where,

  • p is the pattern and replace is the string to replace for the pattern matches in the string str.
  • It returns a new string by replacing the leftmost non-overlapping occurrence of pattern p.
  • replace can be a function or a string.
  • count is the maximum number of patterns to replace. It is an optional value and must be a non-negative integer value. If we don’t provide this, it will replace all strings it finds.

Let’s rewrite the above program to remove all commas using regex:

import re

given_string = input('Enter a string: ')
new_string = re.sub(',', '', given_string)

print('New string: {}'.format(new_string))

Here,

  • we are using re.sub to replace all commas with empty string. The new string returned is stored in new_string.

If you run this program, it will print the below output:

Enter a string: hello,universe
New string: hellouniverse

Enter a string: 1,2,3,4,5
New string: 12345