'Create a tuple from an input in Python
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?
Solution 1:[1]
You could do something like
a = tuple(int(x) for x in a.split(","))
Solution 2:[2]
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)
Solution 3:[3]
It's very simple.
tup = tuple(input("enter tuple"))
print(tup)
This will work.
Solution 4:[4]
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)
Solution 5:[5]
>>> a = input()
(21, 51, 65, 45, 48, 36, 8)
>>> m = eval(a)
>>> type(m)
<class 'tuple'>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jonrsharpe |
| Solution 2 | Martijn Pieters |
| Solution 3 | Alex Waygood |
| Solution 4 | |
| Solution 5 | Tomerikoo |
