How to get back a list object from its string representation?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Dec 31 00:08:29 EST 2008


En Wed, 31 Dec 2008 02:46:33 -0200, Harish Vishwanath  
<harish.shastry at gmail.com> escribió:

>>>> li = [1,2,3]
>>>> repr(li)
> '[1, 2, 3]'
>
> Is there a standard way to get back li, from repr(li) ?

py> eval('[1, 2, 3]')
[1, 2, 3]

eval is like Pandora´s box, all kind of bad things can come from it. Do  
not use it with any user-supplied string.
If you can restrict the values to be just constants, there is a "safe  
eval" recipe in http://code.activestate.com
Also, the json format is pretty much like Python syntax, and safe (I  
think):

py> import json
py> json.dumps([1,'2',3.0])
'[1, "2", 3.0]'
py> json.loads('[1, "2", 3.0]')
[1, u'2', 3.0]

-- 
Gabriel Genellina




More information about the Python-list mailing list