I want to read from stdin five numbers entered as follows:
3, 4, 5, 1, 8
into seperate variables a,b,c,d & e.
How do I do this in python?
Use raw_input() instead of input()
.
# Python 2.5.4
>>> a = raw_input()
3, 4, 5
>>> a
'3, 4, 5'
>>> b = a.split(', ')
>>> b
['3', '4', '5']
>>> [s.strip() for s in raw_input().split(",")] # one liner
3, 4, 5
['3', '4', '5']
The misleadingly names input function does not do what you'd expect it to. It actually evaluates the input from stdin as python code.
In your case it turns out that what you then have is a tuple of numbers in a
, all parsed and ready for work, but generally you don't really want to use this curious side effect. Other inputs can cause any number of things to happen.
Incidentally, in Python 3 they fixed this, and now the input function does what you'd expect.
Two more things:
import string
to do simple string manipulations. Unpacking:
>>> l = (1,2,3,4,5)
>>> a,b,c,d,e = l
>>> e
5