Bruce
Bruce

Reputation: 35275

How to input an integer tuple from user?

Presently I am doing this

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

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

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

Upvotes: 14

Views: 55235

Answers (4)

HEMANTA
HEMANTA

Reputation: 71

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

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304215

Turns out that int does a pretty good job of stripping whitespace, 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)

Upvotes: 7

mjv
mjv

Reputation: 75185

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)])

This is probably less pythonic, but more didactic...

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

tuple(int(x.strip()) for x in raw_input().split(','))

Upvotes: 16

Related Questions