How to remove comma from a string in Python

In this tutorial, we will learn how to remove comma (‘,’) from a string in Python language. Let’s consider the string “c,ode,spe,edy.com“. Now we can remove the commas from the string in two ways i.e. using replace() or using re [Regular Expressions] package.

Remove comma from a string using replace()

Python programming language provides in-built functions to perform operations on a string and replace function is one of those in-built functions. It returns a copy of the string where all the occurrences of a substring are replaced with another substring.
The syntax of the function:
String.replace(old,new,count)

Using this function, we replace the commas in the string with null values.
The code for removing commas from a string using replace() is as follows.

string="c,ode,spe,edy.com" #string
string_dup=string.replace(',',"") #copying the output from replace to another varialbe
print(string_dup) #printing the string without commas

Output:

codespeedy.com

Remove comma from using re or regex package

Python consists of a built-in package called re which can be used to work with regular expressions. This package can be used to work with regular expressions. We can use the function re.sub() of this package to remove commas from the string.  re.sub() function is used to replace the substrings.
The code for it is as follows.

import re #import the package
string="c,ode,spe,edy.com" #input string
print(re.sub(",","",string)) #replace the commas with null and print the string

Output:

codespeedy.com

 

Leave a Reply

Your email address will not be published. Required fields are marked *