47

I have a string of numbers, something like:

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'

I would like to convert this into a list:

example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]

I tried something like:

for i in example_string:
    example_list.append(int(example_string[i]))

But this obviously does not work, as the string contains spaces and commas. However, removing them is not an option, as numbers like '19' would be converted to 1 and 9. Could you please help me with this?

Gino Mempin
  • 19,150
  • 23
  • 79
  • 104
Bart M
  • 635
  • 1
  • 6
  • 13

6 Answers6

91

Split on commas, then map to integers:

map(int, example_string.split(','))

Or use a list comprehension:

[int(s) for s in example_string.split(',')]

The latter works better if you want a list result, or you can wrap the map() call in list().

This works because int() tolerates whitespace:

>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(',')))  # Python 3, in Python 2 the list() call is redundant
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]

Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
12

I guess the dirtiest solution is this:

list(eval('0, 0, 0, 11, 0, 0, 0, 11'))
hendrik
  • 1,802
  • 16
  • 14
  • If the original string of numbers was stored in "python format", this solution will actually adapt to whatever type of data is stored. '0, 0, 0, 11' will map to int type and '0.12, 0.1, 1.2' will map to float type without having to explicitly code for it. – Marcos Nov 10 '16 at 07:56
  • 3
    It could be dirtier, but it's dirty enough to earn you my downvote. Why even post a horrible solution like that? – Aran-Fey Jun 03 '18 at 07:09
7

it should work

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]
lucemia
  • 6,057
  • 5
  • 39
  • 73
7
number_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'

number_string = number_string.split(',')

number_string = [int(i) for i in number_string]
Edd
  • 3,636
  • 3
  • 25
  • 33
Rohit Singh
  • 1,883
  • 2
  • 12
  • 16
  • 1
    Hey Rohit :). Welcome to SO. Do you mind adding a bit explanations to your code? So the next guys coming in have a better idea of what you're doing with your answer :). – Patrice Oct 08 '14 at 15:17
6

You can also use list comprehension on splitted string

[ int(x) for x in example_string.split(',') ]
lejlot
  • 61,451
  • 8
  • 126
  • 152
2

Try this :

import re
[int(s) for s in re.split('[\s,]+',example_string)]