I have a string of numbers like so:
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 it to 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 this code:
example_list = []
for x in example_string:
example_list.append(int(x))
Obviously it does not work, as the string contains spaces and commas. However, even if I remove those, the individual digits of the numbers get converted, giving a result like [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 9, 0, 9, 0, 0, 0, 0, 0, 0, 1, 1]
.
How can I get the desired result?
See also: How to split a string of space separated numbers into integers? . This question adds a small additional consideration: since int
can accept leading and trailing whitespace, there is reason to split on just ,
rather than ,
.
The obvious approach to this problem is a common combination of simple tasks:
- How do I split a string into a list of words?
- How do I parse a string to a float or int?
- How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)?
However, depending on the exact requirements, it can be addressed in other ways. For some cases, the split step may be sufficient on its own. There are other approaches, given in some answers here, to produce different output besides a native Python list
- for example, using the standard library array.array
, or a NumPy array.
Alternately, the problem can be seen as a special case of How to extract numbers from a string in Python? .