python – Create a list of numbers from a string with numbers separated by a space

Question:

There is a line:

'45 30 55 20 80 20 '.

It is necessary to create an array of numbers included in this string:

[45, 30, 55, 20, 80, 20].

I thought for a long time and came only to this code, it just does not work:

for i in range(len(q)):
    if q[i]!=(' '):
        e+=q[i]
    else:
        w.append(int(e))
        e=''
 print(w)   

the problem is that he does not see the last 20, please help

Answer:

You can use the list generator:

s = '45 30 55 20 80 20'
a = [int(x) for x in s.split()]
Scroll to Top