Remove Comma from String in Python

Remove commas from String in Python

💡 Outline

You can remove comma from string in python by using string’sreplace() method.
Syntax:

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.

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:

Output:

remove commas from this string

Explanation

  • Initialized sample string to initial_string
  • Used replace() function to replace commas in string and assigned it to another variable final_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:

Output:

remove commas from this string

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.

Was this post helpful?

Leave a Reply

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