6

Here is my example:

>>> a=input ('some text : ')  # value entered is 1,1
>>> print (a)
1,1

I want as a result a tuple (1, 1)

How can I do this?

jfs
  • 399,953
  • 195
  • 994
  • 1,670

5 Answers5

14

You could do something like

a = tuple(int(x) for x in a.split(","))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
10

You could interpret the input as Python literals with ast.literal_eval():

import ast

a = ast.literal_eval(input('some text: '))

This function will accept any input that look like Python literals, such as integers, lists, dictionaries and strings:

>>> ast.literal_eval('1,1')
(1, 1)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I used this function in one of my programs to take tuple input as well, so I wrapped it with the tuple() function and put it all in a try/except case to prevent things like functions being entered as input and insure that only tuples were entered – samrap Dec 09 '13 at 22:51
  • @samrap: `ast.literal_eval()` doesn't support entering functions. Only literals are supported; strings, booleans, numbers, lists, tuples, dictionaries and `None`. That's it. – Martijn Pieters Dec 09 '13 at 22:53
  • @samrap: You can always use a more explicit method (like jonrsharpe posted) or use `isinstance(result, tuple)` to ensure that only tuples are being entered. – Martijn Pieters Dec 09 '13 at 22:54
0

It's very simple.

 tup = tuple(input("enter tuple"))
 print(tup)    

This will work.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Sudarshan
  • 37
  • 7
  • It will not really work. The input is a string, and passing that to `tuple()` will create a tuple from the string's characters. So for example, for the OP's input of `1,1`, your code will output `('1', ',', '1')` – Tomerikoo Aug 30 '21 at 16:46
0

It can be done in the following way.

a = '3, 5, 7, 23'

out = tuple(map(int, a.split(",")))

print(out)

(3, 5, 7, 23)
J.Jai
  • 597
  • 1
  • 5
  • 9
-2
>>> a = input()
(21, 51, 65, 45, 48, 36, 8)
>>> m = eval(a)
>>> type(m)
<class 'tuple'>
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61