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 comas. 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?
解决方案
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 on Python 3 if you want a list result.
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'
>>> map(int, example_string.split(','))
[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.