14

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

1
  • (n, m) = tuple(map(int, input().split(" ")))
    – quintin
    Sep 22, 2019 at 7:33

4 Answers 4

16
tuple(int(x.strip()) for x in raw_input().split(','))
4
  • How should the user give input now. I tried 4,0...it doesn't work
    – Bruce
    Feb 10, 2010 at 2:03
  • I get the output- Enter source 0,4 Enter target 3,2 ('0', '4') ('3', '2')
    – Bruce
    Feb 10, 2010 at 2:06
  • Ah, I modified my answer slightly after. Compare what you have with what I wrote. Feb 10, 2010 at 2:07
  • 4
    sys.stdin.readline() does have the advantage of working across python2 and python3. In python3 raw_input is renamed to input Feb 10, 2010 at 2:32
7

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

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...

2
  • source and target are themselves tuples. We can use int() on tuples.
    – Bruce
    Feb 10, 2010 at 2:08
  • 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.
    – mjv
    Feb 10, 2010 at 2:15
0
t= tuple([eval(x) for x in input("enter the values: ").split(',')])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.