Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #16422 > unrolled thread

Re: How convert a list string to a real list

Started byPeter Otten <__peter__@web.de>
First post2011-11-30 09:58 +0100
Last post2011-11-30 09:58 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: How convert a list string to a real list Peter Otten <__peter__@web.de> - 2011-11-30 09:58 +0100

#16422 — Re: How convert a list string to a real list

FromPeter Otten <__peter__@web.de>
Date2011-11-30 09:58 +0100
SubjectRe: How convert a list string to a real list
Message-ID<mailman.3148.1322643495.27778.python-list@python.org>
Terry Reedy wrote:

> On 11/30/2011 1:20 AM, 郭军权 wrote:
>> Good after
>> I have a string liststr = '["aaaa","bbbb","ccc"]' ,and I need convert it
>> to a list like list = ["aaaa","bbbb","ccc"],what can id do?
> 
> The easiest -- and most dangerous -- way is
>  >>> eval('["aaaa","bbbb","ccc"]')
> ['aaaa', 'bbbb', 'ccc']
> 
> But DO NOT eval unexamined strings from untrusted sources. The reason is
> that it is much the same as letting an untrusted person sit unsupervised
> as the keyboard of your computer with a command window open. You would
> not want to eval
>    "from os import system; system('<command to delete files>')"
> where '<command...>' is replaced by something obnoxious for your
> operating system.

You can avoid these problems with ast.literal_eval():

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the
    following Python literal structures: strings, numbers, tuples, lists,
    dicts, booleans, and None.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web