pythonstringlistinteger

How to convert a string of space- and comma-separated numbers into a list of int


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 , .

If you want to handle input that follows Python's list syntax (i.e. with surrounding []), see How to convert string representation of list to a list.

The obvious approach to this problem is a common combination of simple tasks:

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? .


Solution

  • 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.