How to convert string into list of integers in Python?

Question:

I have this:

  "1,2,3,4,5,6,7,8,9,0"

And need this:

  [1,2,3,4,5,6,7,8,9,0]

Everything I search for has the example where the string is a list of strings like this:

  "'1','2','3'..."  

those solutions do not work for the conversion I need.

What do I need to do? I need the easiest solution to understand for a beginner.

Asked By: user3486773

||

Answers:

You can use str.split to get a list, then use a list comprehension to convert each element to int.

s = "1,2,3,4,5,6,7,8,9,0"
l = [int(x) for x in s.split(",")]
print(l)
Answered By: Unmitigated

You could use a mapping to convert each element to an integer, and convert the map to a list:

s = "1,2,3,4,5,6,7,8,9,0"
l = list(map(int, s.split(',')))
print(l)
Answered By: Lexpj

You can just call int("5") and you get 5 like a int.

In your case you can try list comprehension expression

a = "1,2,3,4,5,6,7,8,9,0"
b = [int(i) for i in a.split(',')]
print(b)
>> 1,2,3,4,5,6,7,8,9,0
Answered By: Anton Manevskiy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.