Convert comma-separated string to List of Integers in Python

avatar

Borislav Hadzhiev

Last updated: Aug 31, 2022

banner

Photo from Unsplash

Convert comma-separated string to List of Integers in Python #

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

  1. Use the str.split() method to split the string on each occurrence of a 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,2,3,4' my_list = [int(item) for item in my_str.split(',') if item.isdigit()] print(my_list) # 👉️ [1, 2, 3, 4]

We used the str.split() method to split the string on each occurrence of a comma.

main.py
my_str = '1,2,3,4' print(my_str.split(',')) # 👉️ ['1', '2', '3', '4']

The next step is to convert each string in the list to an integer.

We used a list comprehension to iterate over the list of strings.

main.py
my_str = '1,2,3,4' my_list = [int(item) for item in my_str.split(',') if item.isdigit()] print(my_list) # 👉️ [1, 2, 3, 4]
On each iteration, we check if the current string is a digit and if the condition is met, we convert it to an integer.

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

The int class returns an integer object constructed from the provided number or string argument.

If the digits in your string are separated by a comma and one or more spaces, use the str.strip() method to remove the whitespace before checking if the string is a digit.

main.py
my_str = '1, 2, 3, 4' my_list = [int(item) for item in my_str.split(',') if item.strip().isdigit()] print(my_list) # 👉️ [1, 2, 3, 4]

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

If you can be sure the string contains only comma-separated digits, you don't have to use the str.isdigit() method.

main.py
my_str = '1,2,3,4' my_list = [int(item) for item in my_str.split(',')] print(my_list) # 👉️ [1, 2, 3, 4]

If your string may contain a leading or a trailing comma, make sure to exclude any empty string elements from the list.

main.py
my_str = ',1,2,3,4,' my_list = [int(item) for item in my_str.split(',') if item] print(my_list) # 👉️ [1, 2, 3, 4]

The string in the example has a leading and trailing comma, so splitting on a comma returns empty string elements.

main.py
my_str = ',1,2,3,4,' print(my_str.split(',')) # 👉️ ['', '1', '2', '3', '4', '']

You can use a list comprehension to exclude the empty strings from the list.

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.