Python – Convert string with numbers into a list of integers

Question:

I’ve read several questions about this on SO, however, none of them worked out for me – I guess I’m doing something wrong.

I have a string with numbers separated with commas and spaces which looks like this:

my_string = '32, 76, 82, 19, 25'

Now what I would like to have is a list of integers of the numbers in the string above, so I can extract single integers from it like this:

print my_list[2]
>>>82

or

print my_list[4]
>>>25

Thanks in advance!

Asked By: PatFriesen

||

Answers:

Split the problem into two parts.

1 Split the text into a list with the data you need and filter the other.

num_list = my_string.split(',')

2 Convert the data into what type you want it

integers = [int(x) for x in num_list]

Then you might clean it up

integs = [int(x) for x in my_string.split(',')]
Answered By: David Bern

The most pythonic way would be

[int(i) for i in my_string.split(',')]

Of course you can build a simple for loop if you prefer, like

mylist = []
for i in my_string.split(','):
    mylist.append(int(i))

There are plenty of possibilities

Answered By: Glostas