简体   繁体   中英

How to make an input accept spaces?

I need a program in Python , which would ask a user to enter multiple numbers into one line, each number separated by a space. Like Enter your numbers: 2 1 5 8 9 5 and I need for it to print out [2, 1, 5, 8, 9, 5]

But the program I made so far does not accept spaces, how do I change that? Also is there a way to make the number go in order like from smallest to biggest?

Here's what I have so far:

elx = []

el = input("Enter your numbers: ")
for i in el:
    if el.isdigit():
        elx.append(el)
        break
    if not el.isdigit():
        print ("Number is invalid")
        continue

print (elx)

只需按空格分开,使用列表推导检查字符串是否由数字组成:

nums = sorted([int(i) for i in input().split() if i.isdigit()])

Use a try/except and sorted:

while True:
    el = input("Enter your numbers: ")
    try:
        elx = sorted(map(int, el.split()))
        break
    except ValueError:
        print("Invalid input")

If a user can enter negative numbers then isdigit is going to fail.

Also if a user enters 1 2 3 f 5 I think it should be considered a mistake not ignored.

s = input('Gimme numbers! ') # '1 2 3'
s = list(map(int, s.split()))
print(s) # [1, 2, 3]

This generates a list of strings which contain the numbers ( s.split(' ') ), which are in turn converted to ints by the map.

Finally, to sort the list, use sort(s) .

Edit: as stated in the official doc , using split(sep=' ') would throw an exception if some numbers were separated by two spaces, because in that case an empty string would be generated by the split ( '1 2'.split(' ') == ['1', '', '2'] ), and the int() would fail to convert it.

Thanks to Padraic Cunningham for pointing this out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM