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

Discussion in 'Python' started by Gabriel Genellina, Dec 31, 2008.

  1. En Wed, 31 Dec 2008 02:46:33 -0200, Harish Vishwanath
    <> 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
    Gabriel Genellina, Dec 31, 2008
    #1
    1. Advertising

  2. 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
    Steven D'Aprano, Dec 31, 2008
    #2
    1. Advertising

  3. En Wed, 31 Dec 2008 04:27:01 -0200, Steven D'Aprano
    <> escribió:

    > 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]


    That's a very nice addition!

    --
    Gabriel Genellina
    Gabriel Genellina, Dec 31, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hessam
    Replies:
    0
    Views:
    2,178
    Hessam
    Aug 8, 2003
  2. =?Utf-8?B?UmFqZXNoIHNvbmk=?=

    'System.String[]' from its string representation 'String[] Array'

    =?Utf-8?B?UmFqZXNoIHNvbmk=?=, May 4, 2006, in forum: ASP .Net
    Replies:
    0
    Views:
    1,801
    =?Utf-8?B?UmFqZXNoIHNvbmk=?=
    May 4, 2006
  3. Allan Ebdrup
    Replies:
    1
    Views:
    620
    Allan Ebdrup
    Jul 16, 2007
  4. Hessam
    Replies:
    1
    Views:
    231
    Teemu Keiski
    Aug 16, 2003
  5. Hessam
    Replies:
    0
    Views:
    267
    Hessam
    Aug 8, 2003
Loading...

Share This Page