Python is a fantastic programming language with built-in tools, data types, and functions to cover a wide array of applications.
Like most programming languages, Python supports the use of strings which refers to a sequence of characters enclosed in single or double quotes.
In some cases, you may encounter instances where you need to remove commas from a given string sequence. This is a common occurrence in data cleaning or pre-processing.
Method 1 - Using the
The first and most common method of removing commas from a given string is using the
replace method from the
str class. This method allows you to replace a specified character with another specified character.
We can use it to replace commas from a given string with an empty string. This will essentially remove the commas from the string.
Consider the example demonstrated below:
with_commas = "Welcome, to GeekBits,. Glad to have you here." no_commas = with_commas.replace(",", "") print(no_commas)
In this case, the code above will take the commas from the string and replace them with an empty string. The resulting output is as shown:
Welcome to GeekBits. Glad to have you here.
Method 2 - Using List Comprehension
The second technique we can use to remove commas from a string is list comprehension. If you are not familiar, list comprehension in Python refers to a concise method of creating lists in Python from other lists or any iterable object.
List comprehension allows us to perform other actions such as transforming, and filtering elements from the iterable along the way.
The following example demonstrates how we can use list comprehensions to remove commas from a given string.
with_commas = "Welcome, to GeekBits,. Glad to have you here." no_commas = ''.join([char for char in with_commas if char != ',']) print(no_commas)
In this case, we're iterating over each character in the string and only adding it to the new string if it's not a comma.
Method 3 - Using the
We can also combine the
maketrans() method in Python to remove commas from a given string.
translate() method allows us to return a string where the specifiedi characters are replaced with other characters.
maketrans() method on the other hand returns a translation table which we can use with the
translate() function to replace the specified characters.
An example demonstration is as shown:
with_commas = "Welcome, to GeekBits,. Glad to have you here." table = str.maketrans("", "", ",") no_commas = with_commas.translate(table) print(no_commas)
In this case, we use the translation table to replace commas with nothing which removes them from the string.
In this tutorial, we discussed various methods you can use to remove commas from a given Python string.