Convert a comma-separated number to an Integer in Python

avatar

Borislav Hadzhiev

Last updated: Aug 31, 2022

banner

Photo from Unsplash

Convert a comma-separated number to an Integer in Python #

To convert a comma-separated number to an integer:

  1. Use the str.replace() method to remove the commas from the string.
  2. Use the int() class to convert the string to an integer.
main.py
my_str = '1,234,567' # ✅ Convert comma-separated numbers to an integer result = int(my_str.replace(',', '')) print(result) # 👉️ 1234567 # ✅ Convert comma-separated number to multiple integers result = [int(item) for item in my_str.split(',')] print(result) # 👉️ [1, 234, 567] # ------------------- # ✅ convert list of comma-separated numbers to integers my_list = ['1,23', '4,56', '7,89'] result = [int(item.replace(',', '')) for item in my_list] print(result) # 👉️ [123, 456, 789]

The first example converts a comma-separated number to an integer.

main.py
my_str = '1,234,567' result = int(my_str.replace(',', '')) print(result) # 👉️ 1234567

We used the str.replace() method to remove the commas from the string.

main.py
my_str = '1,234,567' print(my_str.replace(',', '')) # 👉️ '1234567'

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

The last step is to use the int() class to convert the string to an integer.

To convert a comma-separated string to a list of integers:

  1. Use the str.split() method to split the string on each comma.
  2. Use a list comprehension to iterate over the list of strings.
  3. Use the int() class to convert each string to an integer.
main.py
my_str = '1,234,567' result = [int(item) for item in my_str.split(',')] print(result) # 👉️ [1, 234, 567]

We used the str.split() method to split the string into a list of strings.

main.py
my_str = '1,234,567' print(my_str.split(',')) # 👉️ ['1', '234', '567']

We then used a list comprehension to iterate over the list.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the int() class to convert the current list item to an integer.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.