Split a String into a List of Integers in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
5 min

banner

# Table of Contents

  1. Split a String into a List of Integers using a list comprehension
  2. Split a string into a list of integers using map()
  3. Split a String into a List of Integers using a for loop
  4. Split a String into a List of Integers using NumPy
  5. Split a String into a List of Integers using re.findall()

# Split a String into a List of Integers using a list comprehension

To split a string into a list of integers:

  1. Use the str.split() method to split the string into a list of strings.
  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 = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # ๐Ÿ‘‰๏ธ ['2', '4', '6', '8', '10'] list_of_integers = [int(x) for x in list_of_strings] print(list_of_integers) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

split string into list of integers

The code for this article is available on GitHub
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 pass the current list item to the int() class and return the result.

You should also use a list comprehension if you need to split the string on each digit.

main.py
my_str = '246810' list_of_ints = [int(x) for x in my_str] print(list_of_ints) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 1, 0]

We iterate directly over the string and on each iteration, we convert the digit that is wrapped in a string to an integer.

# Handling strings that contain non-digit characters

If your string contains non-digit characters, use the str.isdigit() method to check if the current character is a digit before passing it to the int() class.

main.py
my_str = 'x y z 2 4 6 8 10 a' list_of_strings = my_str.split(' ') # ๐Ÿ‘‡๏ธ ['x', 'y', 'z', '2', '4', '6', '8', '10', 'a'] print(list_of_strings) list_of_integers = [int(x) for x in list_of_strings if x.isdigit()] print(list_of_integers) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

handling strings that contain non digit characters

The code for this article is available on GitHub

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.

# Split a string into a list of integers using map()

This is a three-step process:

  1. Use the str.split() method to split the string into a list of strings.
  2. Use the map() function to convert each string into an integer.
  3. Use the list() class to convert the map object to a list.
main.py
# ๐Ÿ‘‡๏ธ String containing integers with space-separator my_str = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # ๐Ÿ‘‰๏ธ ['2', '4', '6', '8', '10'] list_of_integers = list(map(int, list_of_strings)) print(list_of_integers) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

split string into list of integers using map

The code for this article is available on GitHub

If your string doesn't contain a separator between the digits, use the following code sample instead.

main.py
# ๐Ÿ‘‡๏ธ If you want to split the string on each digit my_str = '246810' list_of_ints = [int(x) for x in my_str] print(list_of_ints) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 1, 0]

If the integers in your string are separated with another delimiter, e.g. a comma, pass a string containing a comma to the str.split() method.

main.py
my_str = '2,4,6,8,10' list_of_strings = my_str.split(',') print(list_of_strings) # ๐Ÿ‘‰๏ธ ['2', '4', '6', '8', '10'] list_of_integers = list(map(int, list_of_strings)) print(list_of_integers) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

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

main.py
my_str = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # ๐Ÿ‘‰๏ธ ['2', '4', '6', '8', '10']

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 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # ๐Ÿ‘‰๏ธ ['2', '4', '6', '8', '10'] list_of_integers = list(map(int, list_of_strings)) print(list_of_integers) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

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.

# Split a String into a List of Integers using a for loop

This is a three-step process:

  1. Use the str.split() method to split the string into a list of strings.
  2. Use a for loop to iterate over the list.
  3. Convert each string to an integer and append the result to a new list.
main.py
my_str = '2 4 6 8 10' list_of_integers = [] for item in my_str.split(' '): list_of_integers.append(int(item)) print(list_of_integers) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

split string into list of integers using for loop

The code for this article is available on GitHub

We used a for loop to iterate over the result of calling str.split().

main.py
my_str = '2 4 6 8 10' # ๐Ÿ‘‡๏ธ ['2', '4', '6', '8', '10'] print(my_str.split(' '))

On each iteration of the for loop, we convert the current string to an integer and append the value to the new list.

The list.append() method adds an item to the end of the list.

# Split a String into a List of Integers using NumPy

You can also use the NumPy module to split a string into a list of integers.

main.py
import numpy as np my_str = '2 4 6 8 10' my_list = np.fromstring(my_str, dtype=int, sep=' ').tolist() print(my_list) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

split string into list of integers using numpy

The code for this article is available on GitHub

You can install NumPy by running the following command.

shell
pip install numpy # ๐Ÿ‘‡๏ธ or with pip3 pip3 install numpy

The numpy.fromstring() method returns a new one-dimensional array initialized from the text in a string.

The method takes a sep argument that is used to determine the split character.

main.py
import numpy as np my_str = '2,4,6,8,10' my_list = np.fromstring(my_str, dtype=int, sep=',').tolist() print(my_list) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10]

The tolist method converts a numpy array to a list.

# Split a String into a List of Integers using re.findall()

You can also use the re.findall() method to split a string into a list of integers.

main.py
import re my_str = '2 4 6 8 10 12' list_of_strings = re.findall(r'\d+', my_str) print(list_of_strings) # ๐Ÿ‘‰๏ธ ['2', '4', '6', '8', '10', '12'] list_of_ints = [int(x) for x in list_of_strings if x.isdigit()] print(list_of_ints) # ๐Ÿ‘‰๏ธ [2, 4, 6, 8, 10, 12]

split string into list of integers using re findall

The code for this article is available on GitHub

The re.findall() method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

The first argument we passed to the re.findall() method is a regular expression.

The \d character matches the digits from 0 to 9 (and many other digit characters).

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the range of numbers).

The re.findall() method returns a list containing the matches as strings.

The last step is to use a list comprehension to convert the list of strings to a list of numbers.

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.

Copyright ยฉ 2024 Borislav Hadzhiev