I'm trying to use input
to get the value for a tuple. However, since input
sets the value as a string, I'm trying to unstring it as well. I've found that eval
works for this purpose, but that it should be distrusted. While this will not be a problem as long as I use the code privately, if I were to publicly release it I want to use the best code possible.
So, is there another way of unstringing a tuple
in Python 3?
Here's what I'm currently doing:
>>> a = input("What is the value? ")
What is the value? (3,4)
>>> a
'(3,4)'
>>> eval(a)
(3, 4)
Use the safe version of eval, ast.literal_eval
which is designed exactly for what you are trying to achieve:
from ast import literal_eval
tup = literal_eval(a)
I'd do it like this:
>>> inp = input()
'(3,4)'
>>> tuple(map(int, inp.strip()[1:-1].split(',')))
(3, 4)
where strip
will make sure leading or trailing blanks won't ruin your day.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With