Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: How to get back a list object from its string representation?

Reply
Thread Tools

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

 
 
Gabriel Genellina
Guest
Posts: n/a
 
      12-31-2008
En Wed, 31 Dec 2008 02:46:33 -0200, Harish Vishwanath
<(E-Mail Removed)> 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

 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      12-31-2008
On Wed, 31 Dec 2008 03:08:29 -0200, Gabriel Genellina wrote:

> 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


The ast module in Python 2.6 includes a "literal eval" function:

>>> ast.literal_eval("[1, 2, 3]")

[1, 2, 3]



--
Steven
 
Reply With Quote
 
 
 
 
Gabriel Genellina
Guest
Posts: n/a
 
      12-31-2008
En Wed, 31 Dec 2008 04:27:01 -0200, Steven D'Aprano
<(E-Mail Removed)> escribi:

> On Wed, 31 Dec 2008 03:08:29 -0200, Gabriel Genellina wrote:
>
>> eval is like Pandoras 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

>
> The ast module in Python 2.6 includes a "literal eval" function:
>
>>>> ast.literal_eval("[1, 2, 3]")

> [1, 2, 3]


That's a very nice addition!

--
Gabriel Genellina

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Its a bird, its a plane, its.. um, an Attribute based System? thunk Ruby 14 04-03-2010 10:08 AM
Its a bird, its a plane, its.. um, an Attribute based System? thunk Ruby 0 04-01-2010 10:25 PM
Its a bird, its a plane, no ummm, its a Ruide thunk Ruby 1 03-30-2010 11:10 AM
Determining method type given its string name presentation and its corresponding object reference. Apple Python 3 08-01-2005 03:16 AM



Advertisments