How to split strings into a list of integers in Python?

Renesh Bedre    2 minute read

You can use two methods to split the strings into a list of integers in Python 3:

  • Using a list Comprehension (more Pythonic)
  • Using a map() function

Using list Comprehension function

List Comprehension is more pythonic way to convert string into a list of int. In this method, we pass a int function to each element of a string of list within a list.

# input string
s = '12 34 55 66 88 78' 

# convert string into list of int
int_list = [int(i) for i in s.split()]
# output
[12, 34, 55, 66, 88, 78]

Using map() function

In this method, you need to use str.split(), map(), and list() functions.

# input string
s = '12 34 55 66 88 78' 

# convert string into list of int
int_list = list(map(int, s.split()))
# output
[12, 34, 55, 66, 88, 78]

Step-by-step explanation of how these three function works,

We split the string using str.split() function. The syntax for the split function is str.split(separator, maxsplit).

separator: The separator for the split. The default is a whitespace character. This is optional. maxsplit: Number of splits to output. The default is -1 which outputs all splits. If it is 1, it will give 2 splits.

Examples of str.split(),

# split using comma
s = '12,34,55,66,88,78'
s.split(',')
# output
['12', '34', '55', '66', '88', '78']

# split into 2 values
s.split(',', 1)
# output
['12', '34,55,66,88,78']

Now, convert each element in list into int using the map() function. In above example, the map() passes a int function to all the elements of iterable (list).

The syntax for the map function is map(function, iterable). The map function returns an object (in Python 3) and hence you need to use the list() function to see the list.

function: Provide any function which will be applied to each element of the iterable such as list iterable: Provide a iterable to apply the function.

Examples of map(),

# convert string numbers into int
s = ['12', '34', '55', '66', '88', '78']
map(int, s)
# output
<map object at 0x0000021432D97FA0>

# use list function
list(map(int, s))
# output
[12, 34, 55, 66, 88, 78]

Enhance your skills with courses Python

This work is licensed under a Creative Commons Attribution 4.0 International License

Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.

Tags:

Updated: