Home » Python » Remove Comma from List in Python

Remove Comma from List in Python

To remove commas from a list in Python, use the str.replace() method.

str.replace() in Python replaces the specified phrase in the string with the new phrase. Use the replace() method to remove all instances of a comma from a list in Python. For example, replacing all instances of character ‘,’ with ”

In this example, we will discuss how to use the str.replace() in Python to remove commas from a list of strings.

Use str.replace() to remove comma from a string

To remove a comma from a string in Python:

  1. Call the str.replace() on the list of strings and pass a comma to search for a replacement and a new character for a replacement.
  2. The replace() returns a copy of the string in which all occurrences of commas are replaced by a new character ”.
list_of_strings = ["Hi,there!","remove,commas,from,a list"]
print(list_of_strings)

updated_list = [str.replace(",","") for str in list_of_strings]
print(updated_list)

In the above Python program, we pass the following parameters to replace():

  1. list_of_strings variable stores the list of strings that contains commas in it.
  2. Use the str.replace() with [str for str in list] to remove commas from the list.
  3. character ‘,’ to search for in the list of strings.
  4. replacement character ”. It will replace all occurrences of commas ‘,’ with ”

It will return the copy of the list of strings and store it in the updated_list variable and print using print() Python.

The output of the above program after removing commas from a list of strings is:

['Hi,there!', 'remove,commas,from,a list']

['Hithere!', 'removecommasfroma list']

Cool Tip: How to remove a character from the list of strings in Python!

Conclusion

I hope the above article on how to remove commas from the list in Python using str.replace() is helpful to you.

You can find more topics about the Python tutorials on the DataVisualizr Home page.

Leave a Comment