0

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!

PatFriesen
  • 21
  • 1
  • 1
  • 2
  • 2
    If you've read several questions and they didn't work then show your efforts – EdChum Sep 13 '16 at 11:19
  • 1
    The delimeter you have is ', ' use that to split your numbers in to a list. integs = [int(x) for x in my_string.split(', ')] – David Bern Sep 13 '16 at 11:21
  • my_list = map(lambda x: int(x), my_string.split(',')) – BPL Sep 13 '16 at 11:33
  • @BPL The lambda is unnecessary, see http://stackoverflow.com/a/3477535/4014959 (and my comment on that answer). – PM 2Ring Sep 13 '16 at 11:41
  • @PM2Ring Oh, yeah, thx. Also, to get the same result with py2/3 maybe you should do `list(map(int, my_string.split(',')))` – BPL Sep 13 '16 at 11:50

2 Answers2

2

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(',')]
David Bern
  • 778
  • 6
  • 16
0

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

Glostas
  • 1,090
  • 2
  • 11
  • 21