raw_input multiple inputs around strings

93 views Asked by At

Is it possible for the user to input multiple variables around strings (so they are there as they type). I want the user to input numbers x,y,u,v like

(x,y) to (u,v) where the brackets and commas are there to guide their input.

I hope it to be something (I know this code is wrong) like:

a1, a2, a3, a4 = raw_input("("+x1+", "+x2+") to ("+x3+", "+x4+")").split()

where the i'th a varaible take the value of the i'th x value.

1

There are 1 answers

3
fferri On BEST ANSWER

Your code is not wrong.

It actually works:

>>> x1,x2,x3,x4 = 'xyuv'
>>> a1, a2, a3, a4 = raw_input("("+x1+", "+x2+") to ("+x3+", "+x4+")").split()
(x, y) to (u, v)1 2 3 4
>>> a1
'1'
>>> a2
'2'
>>> a3
'3'
>>> a4
'4'

However:

  • the output (a1,a2,a3,a4) are strings.
  • it requires a strict format of 4 numbers separated by spaces. deviations from this format result in a variety of exceptions being thrown by the interpreter.

You can solve first problem with map(int, ...) this way:

a1, a2, a3, a4 = map(int, raw_input("("+x1+", "+x2+") to ("+x3+", "+x4+")").split())

For the second problem, maybe you can surround the code with a try: ... except: ..., and also surround it with a while True such that until it gets an exception, it repeats it:

while True:
    try:
        a1, a2, a3, a4 = map(int, raw_input("("+x1+", "+x2+") to ("+x3+", "+x4+")").split())
        break
    except:
        continue

Here I try to feed it some bad input, and finally a good input (it terminates when it gets good input):

(x, y) to (u, v)a
(x, y) to (u, v)a a a a
(x, y) to (u, v)1 2 3 4