Search code examples
pythonstringlistintegertype-conversion

Python - Convert string with numbers into a list of integers


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!


Solution

  • 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(',')]