string to list when the contents is a list
Matt McCredie
mccredie at gmail.com
Wed Feb 17 19:51:39 EST 2010
Wes James <comptekki <at> gmail.com> writes:
>
> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"
>
> The "[]" is simple since I can just check if value == "[]" then return []
>
> But with "['a','b']" I have tried and get:
>
> a="['a','b']"
>
> b=a[1:-1].split(',')
>
> returns
>
> [ " 'a' "," 'b' " ]
>
> when I want it to return ['a','b'].
>
> How can I do this?
eval will work, but has a safety issue. It also has the issue of evaluating any
and everything that a user might pass in.
If you are using python 2.6 check out ast.literal_eval. It uses python's built
in ast parser to generate an AST and then traverses it to generate a python
object. Unlike eval though, it will raise an exception if anything other than a
literal is represented in the string. I have used the same function in python
2.5 (copied from 2.6) and it works just fine.
Here is a version modified from the code in python 2.6 that should only parse
lists of strings:
from _ast import List, Str, PyCF_ONLY_AST
def parse(expr, filename='<unknown>', mode='exec'):
"""
Parse an expression into an AST node.
Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
"""
return compile(expr, filename, mode, PyCF_ONLY_AST)
def list_eval(text):
"""
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.
"""
node = parse(text, mode='eval').body
if not isinstance(node, List):
raise ValueError('malformed string')
def _convert(node):
if isinstance(node, Str):
return node.s
raise ValueError('malformed string')
return list(map(_convert, node.elts))
Matt McCredie
More information about the Python-list
mailing list