5

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 !

dkentre
  • 289
  • 3
  • 5
  • 10

3 Answers3

7

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.

Shashank
  • 13,713
  • 5
  • 37
  • 63
  • 2
    Further clarity for OP: .split() is taking the string and turning it into a list. It breaks up the string around whitespace by default, but you can pass it other things like `user_input.split(",")` would be the solution here if you wanted the user to yield the digits by entering "31,722,9191" – DHandle Sep 15 '13 at 02:24
  • I dunno which version of python is this,but now you can only write ```a,b,c=input("enter 3 ints")``` – Sahin Apr 19 '21 at 19:26
3
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}")
mkhaled
  • 31
  • 2
1

You can also do like this

a, b, c = [int(x) for x in input("Please enter the numbers: ").split()]
Nithin R
  • 761
  • 6
  • 6