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

James Mills prologic at shortcircuit.net.au
Wed Dec 31 00:02:21 EST 2008


On Wed, Dec 31, 2008 at 2:46 PM, Harish Vishwanath
<harish.shastry at gmail.com> wrote:
> Hello,
> Consider :
>>>> li = [1,2,3]
>>>> repr(li)
> '[1, 2, 3]'
> Is there a standard way to get back li, from repr(li) ?

Normally you would use eval(..) however this is
considered by many to be evil and bad practise (especially by me!)

I would advise you use pickle instead.

Using eval (evil):

>>> li = [1, 2, 3]
>>> s = repr(li)
>>> s
'[1, 2, 3]'
>>> lii = eval(s)
>>> lii
[1, 2, 3]
>>> lii == li
True

Using pickle (better):

>>> from pickle import dumps, loads
>>> li = [1, 2, 3]
>>> s = dumps(li)
>>> s
'(lp0\nI1\naI2\naI3\na.'
>>> lii = loads(s)
>>> lii
[1, 2, 3]
>>> lii == li
True

cheers
James



More information about the Python-list mailing list