Change a string of integers separated by spaces to a list of int

后端 未结 6 1020
不知归路
不知归路 2020-12-25 11:33

How do i make something like

x = \'1 2 3 45 87 65 6 8\'

>>> foo(x)
[1,2,3,45,87,65,6,8]

I\'m completely stuck, if i do it by inde

6条回答
  •  长发绾君心
    2020-12-25 12:05

    Assuming you only have digits in your input, you can have something like following:

    >>> x = '1 2 3 45 87 65 6 8'
    >>> num_x = map(int, filter(None, x.split(' ')))
    >>> num_x
    [1 2 3 45 87 65 6 8]
    

    This will take care of the case when the digits are separated by more than one space character or when there are space characters in front or rear of the input. Something like following:

    >>> x = ' 1 2 3  4 '
    >>> num_x = map(int, filter(None, x.split(' ')))
    >>> num_x
    [1, 2, 3, 4]
    

    You can replace input to x.split(' ') to match other delimiter types as well e.g. , or ; etc.

提交回复
热议问题