Convert a string to a list of integers in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Convert a string to a list of integers in Python #

To convert a string to a list of integers:

  1. Use the str.split() method to split the string into a list of strings.
  2. Use the map() function to convert each string to an integer.
  3. Use the list() class to convert the map object to a list.
main.py
# ✅ Convert comma-separated string to list of integers my_str = '2,4,8' result = list(map(int, my_str.split(','))) print(result) # 👉️ [2, 4, 8] # ------------------------------------------------ # ✅ Convert space-separated string to list of integers my_str = '2 4 8' result = list(map(int, my_str.split(' '))) print(result) # 👉️ [2, 4, 8] # ------------------------------------------------ # ✅ Convert string of numbers (no separator) to list of integers my_str = '248' result = [int(d) for d in my_str] print(result) # 👉️ [2, 4, 8]
If the integers in your string are separated with another delimiter, e.g. a hyphen, pass a string containing a hyphen to the str.split() method.

The first step is to use the str.split() method to split the string into a list.

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

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

The next step is to convert each string in the list to an integer using the map() function.

main.py
my_str = '2,4,8' result = list(map(int, my_str.split(','))) print(result) # 👉️ [2, 4, 8]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

On each iteration, we pass the string to the int() class to convert it to an integer.

The map() function returns a map object, so we have to use the list() class to convert it to a list.

An alternative to using the map() function is to use a list comprehension.

main.py
my_str = '2,4,8' result = [int(d) for d in my_str.split(',')] print(result) # 👉️ [2, 4, 8]
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

If you have a string that contains digits without a separator, use a list comprehension to convert each digit to an integer.

main.py
my_str = '248' result = [int(d) for d in my_str] print(result) # 👉️ [2, 4, 8]

We used a list comprehension to iterate over the list of strings and used the int() class to convert each string 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.