3 values (numbers) in 1 input separation. Python 3

北战南征 提交于 2021-01-04 07:30:06

问题


I'm working on a code right now that a part of it requires to ask the user for 3 different numbers in one line ( could be any number of digits in each number). Say I ask the user for the input and he enters : "31 722 9191". A space is required between the numbers. How would you go about separating these numbers and assigning a variable to each one of them. So for example 31 would be "A", 722 would be "B" and so on... What I've got so far:

user_input = input(" Please enter the numbers: ")

Thanks !


回答1:


Use a combination of split and sequence unpacking.

user_input = user_input(" Please enter the numbers: ")
a, b, c = user_input.split()

split will take your string of numbers, say "x y z", and turn it into a list of elements in the string where the elements are all the words in the string that are separated by spaces. Thus split will yield the string ['x', 'y', 'z'] for input 'x y z'.

Since a list is a form of sequence, its elements can be "unpacked" and assigned to a list of variables of your choosing.




回答2:


x = (input("Enter 3 user inputs: ").split())

a = int(x[0])
b = int(x[1])
c = int(x[2])

print(f"A: {a}, B: {b}, C: {c}")


来源:https://stackoverflow.com/questions/18808307/3-values-numbers-in-1-input-separation-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!