Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unstring a list/tuple without eval [duplicate]

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)
like image 687
Fred Barclay Avatar asked Dec 12 '15 23:12

Fred Barclay


2 Answers

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)
like image 123
Padraic Cunningham Avatar answered Sep 27 '22 21:09

Padraic Cunningham


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.

like image 29
timgeb Avatar answered Sep 27 '22 20:09

timgeb