How to enter an integer tuple from a user?

I'm currently doing this

print 'Enter source' source = tuple(sys.stdin.readline()) print 'Enter target' target = tuple(sys.stdin.readline()) 

but the source and target become string tuples in this case with \ n at the end

+9
python
source share
4 answers
 tuple(int(x.strip()) for x in raw_input().split(',')) 
+12
source share

It turns out that int does a pretty good job of removing spaces, so there is no need to use strip

 tuple(map(int,raw_input().split(','))) 

For example:

 >>> tuple(map(int,"3,4".split(','))) (3, 4) >>> tuple(map(int," 1 , 2 ".split(','))) (1, 2) 
+6
source share

If you still want the user to be prompted twice, etc.

 print 'Enter source' source = sys.stdin.readline().strip() #strip removes the \n print 'Enter target' target = sys.stdin.readline().strip() myTuple = tuple([int(source), int(target)]) 

It is probably less pythonic, but more didactically ...

+1
source share
 t= tuple([eval(x) for x in input("enter the values: ").split(',')]) 
0
source share

All Articles