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

后端 未结 6 1034
不知归路
不知归路 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:22

    Just to make a clear explanation.

    You can use the string method str.split() which split the string into a list. You can learn more about this method here.

    Example:

    def foo(x):
        x = x.split() #x is now ['1','2','3','45', ..] the spaces are removed.
        for i, v  in enumerate(x): #Loop through the list
            x[i] = int(v) #convert each element of v to an integer
    

    That should do it!

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

提交回复
热议问题