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.