Convert a String to a List of integers in Python

This tutorial will discuss about unique ways to convert a string to a list of integers in Python.

Table Of Contents

Method 1: Using List Comprehension

Iterate over all characters in string using a for loop inside a List Comprehension. During iteration, convert each digit character in string into an integer, using the int() method. The List Comprehension will return a new list of converted integers.

Let’s see the complete example,

strValue = "11122022"

# Convert a string into a list of integers
listOfInts = [int(ch) for ch in strValue]

print(listOfInts)

Output

[1, 1, 1, 2, 2, 0, 2, 2]

Method 2: Using map() function

Pass int() method and the string value in the map() function. It will apply int() function on all the characters in string, and convert them to integers (assuming all the characters in string are digits only). The map() function returns a mapped object, containing all these converted integers. We can pass that to the list() function to get a list of integers.

Let’s see the complete example,

strValue = "11122022"

# Convert a string into a list of integers
listOfInts = list(map(int, strValue))

print(listOfInts)

Summary

We learned about different ways to convert a string of digits into a list of integers in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top