Last modified: Jan 19, 2023 By Alexander Williams
How to Remove Comma in Number Python
Are you dealing with a string containing commas and looking for a way to remove them? If so, you've come to the right place.
Python offers various methods to remove commas from numbers, depending on the number type and the specific use case. In this article, we will explore two common methods for achieving this.
If you are ready, Let's go through each method.
1. Using the Replace Method
One of the simplest ways to remove commas from a number is using the replace() built-in function. This function replaces a specified substring with another substring.
Here is the syntax:
string.replace(oldsubstring, newsubstring, count)
- oldsubstring: is the substring you want to replace.
- newsubstring: is the substring you want to replace it with
- count: how many occurrences of the old value do you want to replace
Now let's see how to use replace() to remove commas from a number.
num = "10,000" # Number new_num = num.replace(",", "") # Remove commas from number print(new_num)
As you can see, We've replaced the comma with an empty value. In other words, we've removed the comma from the number. Now let's see an example with multiple numbers.
Now, let's say we have a list of numbers with commas:
numbers_with_commas = ["1,234", "5,678", "9,012"] # Numbers with commas numbers_without_commas =  # list to store the numbers without commas for num in numbers_with_commas: # Iterate over each number in the list new_num = num.replace(",", "") # Remove commas from number numbers_without_commas.append(new_num) # Append the new number the numbers_without_commas print(numbers_without_commas)
['1234', '5678', '9012']
2. Using the Regex
Another way to remove commas from numbers is by using regular expressions or Regex. Regex lets you check if a particular string matches a given regular expression manipulation.
However, the syntax of re.sub() is similar to that of the built-in str.replace() method, but there are a few differences in the syntax. Here is an example:
import re num = "10,000" # Number new_num = re.sub(",", "", num) # remove commas from number print(new_num)
Challenge and solution
It is important to keep in mind that when concatenating the number obtained by removing the commas with another number, You will get a TypeError error:
num = "10,000" # Number new_num = num.replace(",", "") # remove commas from number print(new_num + 90)
TypeError: can only concatenate str (not "int") to str
For more information about this Error, Please read TypeError: can only concatenate str (not 'int') to str. However, we must use the int() built function to solve this issue.
num = "10,000" # Number new_num = num.replace(",", "") # remove commas from number print(int(new_num) + 90)
Simply, int() converts a string to an integer.
In conclusion, you can use different methods to remove commas from a number in python, replace() or re.sub(). Both of these methods work perfectly.