How to Remove a Comma from a String? 5 Best Ways

5/5 - (1 vote)

Problem Formulation and Solution Overview

In this article, you’ll learn how to remove a comma/commas from a string in Python.

To make it more fun, we have the following running scenario:

We have a famous proverb, written by Desiderius Erasmus, that contains a comma or commas that need to be removed as it was not in the original. So let’s look at five (5) ways to accomplish this task.

💬 Question: How would we write Python code to remove a comma/commas from a String?

We can accomplish this task by one of the following options:


Preparation

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import re

Method 1: Use replace()

This method uses replace() from Python’s built-in string library to remove the comma/commas and return a new string with the modifications made.

Example 1: Remove all Commas from a String

proverb = 'In the valley, of the blind the one eyed man is king.'
result  = proverb.replace(',', '')
print(result)

This code declares a string containing a single comma and saves it to proverb.

Next, replace() is appended to the string (proverb.replace()), and the arguments passed to the same are as follows:

  • The first argument is the character to replace/remove (',').
  • The second argument is the character to replace the first argument with (''). In this case, an empty string.

Finally, the result is saved and output to the terminal.

Output

In the valley of the blind the one-eyed man is king.

OR

Example 2: Remove One Comma from a String

What if your string had two (2) or more commas? How could we remove only the first occurrence and leave the remaining?

proverb = 'In the valley, of the blind, the one eyed man is king.'
result  = proverb.replace(',', '', 1)
print(result)

This could be done by passing a third argument to replace(): the number of occurrences (count) to remove. In this case, the first comma is removed, and the other remains (proverb.replace(',', '', 1)).

Finally, the result is saved and output to the terminal.

💡 Note: When passing count to replace(), it starts removing the specified number of the selected character(s) from the left of the string.

Output

In the valley of the blind, the one-eyed man is king.

Perfect!


Method 2: Use Regex

This method calls the re library, removes all specified character occurrences, and returns a new string with modifications.

proverb = 'In the valley, of the blind the one eyed man is king.'
result  = re.sub(',', '', proverb)
print(result)

This code declares a string containing a single comma and saves it to proverb.

Next, re.sub() is called with three (3) arguments:

  • The first argument is the character to replace/remove (',').
  • The second argument is the character to replace the first argument with (''). In this case, an empty string.
  • The third argument is the string to apply this to (proverb).

Finally, the result is saved and output to the terminal.

Output

In the valley of the blind the one-eyed man is king.

💡 Note: Unlike Method 1, this method does not offer the option to enter a specified count (number of occurrences) to remove. In this case, all occurrences will be removed.


Method 3: Use List Comprehension

This method uses List Comprehension and a for to loop to evaluate, then split the line on the specified character (proverb.split(',')) and remove same. A List is returned.

proverb = 'In the valley, of the blind, the one eyed man is king.'
result  = [x.strip() for x in proverb.split(',')]
print(result)

This code declares a string containing two (2) commas and saves it to proverb.

Next, split() is called and passed the character to split the string on (proverb.split(',')).

Finally, the result is saved and output to the terminal in a List format containing three (3) elements.

Output

['In the valley', 'of the blind', 'the one-eyed man is king.']

Method 4: Use a Lambda and split()

This method uses a Lambda to loop through, strip(), and split() the string on a specified character. Then, the specified character(s) are removed, and the results convert to a map() object, then to a List.

proverb = 'In the valley, of the blind, the one-eyed man is king.'
result = list(map(lambda s: s.strip(), proverb.split(',')))
print(result)

This code declares a string containing two (2) commas and saves it to proverb.

Next, a Lambda is used to strip() the string, and split() on the comma character (proverb.split(',')), creating three (3) elements.

When map() is applied to the Lambda , an object similar to the following is created.

<map object at 0x000001A7E80E6D40>

Finally, the object is converted to a List, and the result is sent to the terminal in this format containing three (3) elements.

Output

['In the valley', 'of the blind', 'the one-eyed man is king.']

Method 5: Use replace() and split()

This simple method uses replace() and split() on one line to remove all occurrences of the specified character (',') and return a List.

proverb = 'In the valley, of the blind, the one-eyed man is king.'
result  = proverb.replace(',', '').split(',')
print(result[0])

This code declares a string containing two (2) commas and saves it to proverb.

Next, replace() is appended to proverb, which removes the specified character(s) from the string. Then, split() splits the line on the specified character (',').

A list containing one (1) element returns.

Finally, to output result without the surrounding brackets [0] must be applied to the end.

Output

In the valley of the blind the one-eyed man is king.

Bonus: Remove Commas from a Text File

What happens if you want to remove a specified character from all lines in a flat-text file? A simple one-liner solution that removes commas and newline characters is based on the List Comprehension expression [line.replace(',', '').replace('\n', '') for line in open('file.txt')].

# One-Liner:
result = [line.replace(',', '').replace('\n', '') for line in open('proverbs.txt')]
print(result)

Contents of proverbs.txt

In the country, of the blind the one-eyed man is king.
In the valley of the blind, the one-eyed man is king.
In the city of the, blind the one-eyed man is king.

This code opens and reads the contents of proverbs.txt one line at a time.

Each line is evaluated, and the specified character is removed (','). This is called once again as we also want to remove the newline character (‘\n‘).

Finally, the output saves to result and sent to the terminal in a List format containing three (3) elements.

Output

 ['In the country of the blind the one-eyed man is king.',
 'In the valley of the blind the one-eyed man is king.',
 'In the city of the blind the one-eyed man is king.']

Summary

These five (5) methods of removing a comma/commas from a string should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!