How convert a list string to a real list

Hidura hidura at gmail.com
Wed Nov 30 17:48:37 EST 2011


Why you don't make this "['1','2','3']".strip("[]").split(',') work for me
El nov 30, 2011 10:16 p.m., "Terry Reedy" <tjreedy at udel.edu> escribió:

> On 11/30/2011 3:58 AM, Peter Otten wrote:
>
>> 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.
>>
>
> I keep forgetting that someone thought to solve the problem of eval being
> both convinient and dangerous. Maybe if I type it once, I will remember.
> >>> import ast
> >>> ast.literal_eval('["aaaa","**bbbb","ccc"]')
> ['aaaa', 'bbbb', 'ccc']
>
> I think it would be better if safe_eval were available as an easily
> accessible builtin and dangerous_eval were tucked away in a module ;-).
>
> --
> Terry Jan Reedy
>
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111130/ccc41393/attachment.html>


More information about the Python-list mailing list