Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input an integer tuple from user?

Tags:

python

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

like image 395
Bruce Avatar asked Feb 10 '10 01:02

Bruce


People also ask

How do you input an int tuple in Python?

We can use int() on tuples. Sorry, the desired output is unclear. At any rate, the string. strip() and the int() should allow you to get exactly what you need, be it two tuples of a single integer each, or one tuple with the source and target values.

How do you input an integer as a user?

To use them as integers you will need to convert the user input into an integer using the int() function. e.g. age=int(input("What is your age?")) This line of code would work fine as long as the user enters an integer.

How do I input from user a list of tuples in Python?

List comprehension along with zip() function is used to convert the tuples to list and create a list of tuples. Python iter() function is used to iterate an element of an object at a time. The 'number' would specify the number of elements to be clubbed into a single tuple to form a list.


2 Answers

tuple(int(x.strip()) for x in raw_input().split(','))
like image 70
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 17:09

Ignacio Vazquez-Abrams


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)
like image 21
John La Rooy Avatar answered Sep 20 '22 17:09

John La Rooy