How to Convert a String to a List of Integers

Rate this post

Problem Formulation and Solution Overview

In this article, you’ll learn how to convert a String representation of a list consisting of multiple numbers to a list of integers in Python.

🌎 Related Tutorial: How to convert a list of integers to a list of strings in Python?

To make it more fun, we have the following running scenario:

The Finxter Academy has generated unique IDs for new users. However, these IDs were inadvertently saved as a String. They need to be converted to a List of Integers.

Example:

  • Given string: "30022145, 30022192, 30022331, 30022345, 30022359"
  • Desired list: [30022145, 30022192, 30022331, 30022345, 30022359]

πŸ’¬ Question: How would we write code to convert this string?

We can accomplish this task by one of the following options:


Method 1: Use List Comprehension

This option uses Python’s built-in functions split() and int() in conjunction with List Comprehension to convert a String into a List of Integers.

string_ids = ("30022145, 30022192, 30022331, 30022345, 30022359").split(',')
int_ids    = [int(x) for x in string_ids]
print(int_ids)

Above declares a String containing five (5) Finxter IDs inside brackets:
("30022145, 30022192, 30022331, 30022345, 30022359").

πŸ’‘Note: This string is wrapped inside brackets () to allow us to append another function (split()).

Then split() is appended to the above String, and the comma (,) character is passed as an argument. This argument lets split() know where to break the String. The results save to string_ids.

At this point, strings_ids contains a List of Strings:

['30022145', ' 30022192', ' 30022331', ' 30022345', ' 30022359']

Next, List Comprehension is used to loop through each element (ID) and convert it to an Integer value (int(x)). The results save to int_ids and are output to the terminal as a List of Integers.

[30022145, 30022192, 30022331, 30022345, 30022359]
List Comprehension Python List of Lists

Method 2: Use Regex

This option requires an additional library, regex, to perform the task. The function re.findall() is called to locate, extract and convert the data into a List of Integers.

import re
string_ids = "30022145 30022192 30022331 30022345 30022359"
string_ids = re.findall('\d+', string_ids)
int_ids    = [int(x) for x in string_ids]
print(int_ids)

Above, the regex library is imported. Click here if this library requires installation.

Then, a string containing five (5) Finxter IDs separated by the space character (' ') is declared and saved to string_ids.

Next, re.findall() is called and passed two (2) arguments:

  • A regex pattern ('\d+'). This pattern searches for one (1) or more decimals (integers) inside the second argument (each match is separated with the space (' ') character).
  • The second argument string_ids, declared earlier.

At this point, strings_ids contains a List of Strings.

['30022145', '30022192', '30022331', '30022345', '30022359']

Finally, List Comprehension is used to loop through each element (ID) and convert it to an Integer value (int(x)). The results save to int_ids and are output to the terminal as a List of Integers.

[30022145, 30022192, 30022331, 30022345, 30022359]
5 must have skills to become a programmer (that you didn't know)

Method 3: Use isdigit()

This option uses List Comprehension in conjunction with isdigit() to loop through the String to extract and convert the data.

string_ids = "30022145 30022192 30022331 30022345 30022359"
int_ids    = [int(x) for x in string_ids.split() if x.isdigit()]
print(int_ids)

Above, a String containing five (5) Finxter IDs separated by the space character (' ') is declared and saved to string_ids.

Then, List Comprehension is used to loop through string_ids split into substrings (elements) and convert each element to an Integer if it is a digit (x.isdigit()). The results save to int_ids and are output to the terminal as a List of Integers.

πŸ’‘Note: By default, split() assumes the separating character is a space.
If true, no argument needs to be passed.

[30022145, 30022192, 30022331, 30022345, 30022359]
Python String Methods [Ultimate Guide]

✨ A Finxter Favorite!
Minimum Code, Maximum Results!


Method 4: Use List, Map() and Split()

This option uses List, map(), and split() to extract and convert the String into a List of Integers.

string_ids = "30022145 30022192 30022331 30022345 30022359"
int_ids    = list(map(int, string_ids.split()))
print(int_ids)

Above, a String containing five (5) Finxter IDs separated by the space character (' ') is declared and saved to string_ids.

Then, the map() function is called and passed two (2) parameters:

The results convert to a List of Integers, saves to int_ids and outputs to the terminal.

[30022145, 30022192, 30022331, 30022345, 30022359]
Mastering the Python Map Function [+Video]

Method 5: Use NumPy

This option requires an additional library, NumPy, to perform the task. The function np.fromstring() is called to extract and convert the data into a List of Integers.

string_ids = "30022145 30022192 30022331 30022345 30022359"
int_ids = np.fromstring(string_ids, dtype=int, sep=' ')
print(int_ids)

Above, the NumPy library is imported. Click here if this library requires installation.

Then, a String containing five (5) Finxter IDs separated by the space character (' ') is declared and saved to string_ids.

Next, np.fromstring() is called and passed three (3) arguments:

  • The String: string_ids.
  • The Data Type: dtype=int.
  • The Separating Characer: sep= ' '.

The results save to int_ids and are output to the terminal.

[30022145 30022192 30022331 30022345 30022359]
NumPy Tutorial - Everything You Need to Know to Get Started

Bonus: Split String Every Nth Character

What happens if the String does not have a separating character: it’s all one (1) string? How could we split this String every eight (8) characters? With slicing, of course!

string_ids = "3002214530022192300223313002234530022359"
int_ids    = [int(string_ids[i:i+8]) for i in range(0, len(string_ids), 8)]
print(int_ids)

Above, a String containing five (5) Finxter IDs joined together is declared and saved to string_ids.

Then, slicing is used to iterate through string_ids, splitting it every 8th character and converting it to an Integer. The results save to int_ids and output to the terminal.

[30022145, 30022192, 30022331, 30022345, 30022359]
The Ultimate Guide to Slicing in Python

✨ Another Finxter Favorite!
Minimum Code, Maximum Results!


Summary

These methods of converting a String to a List of Integers should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor

πŸ‘±β€β™€οΈ Programmer 1: We have a problem
πŸ§”β€β™‚οΈ Programmer 2: Let’s use RegEx!
πŸ‘±β€β™€οΈ Programmer 1: Now we have two problems

… yet – you can easily reduce the two problems to zero as you polish your “RegEx Superpower in Python“. πŸ™‚