💡 Outline
You can remove comma from string in python by using string’s
replace()
method.
Syntax:
123 final_string=initial_string.replace(',',"")
In this tutorial, we will take a sample string with a couple of commas in it and we will see some methods to remove comma from string in Python.
Table of Contents
Using replace()
function to remove comma from string in Python
There are a lot of built-in functions Python which helps us to carry various operations on strings. One of the built-in functions is the replace()
function. This function is used to replace one string with another and return the new string. The changes that are to be made are mentioned in the function argument.
Example:
1 2 3 4 5 |
initial_string= "re,move com,mas f,rom this, string" final_string=initial_string.replace(',',"") print(final_string) |
Output:
Explanation
- Initialized sample string to
initial_string
- Used
replace()
function to replace commas in string and assigned it to another variablefinal_string
- As you can see, we have replaced the comma with empty string.
- Printed the
final_string
Using re
or RegEx package function to remove comma from string in Python
The re
or RegEx package is a built-in python package that helps in dealing with regular expressions. This package helps in the manipulation of special sequences of characters and strings.
This package has a function called the re.sub()
function which helps in replacing characters that keep on repeating again and again with another character or sub-string.
Example:
1 2 3 4 5 |
import re initial_string="re,move com,mas f,rom this, string" print(re.sub(",","",initial_string)) |
Output:
Explanation
- Imported RegEx package that is pre-installed in python
- Stored string in variable named
initial_string
- Used
re.sub
method to remove commas in string. Here, we have replaced all the commas with empty string. - You can either assign returned value of the
re.sub
method or directly print it as we did in above code.
That’s all about how to remove comma from String in Python.