| Store | Cart

How to convert string to list without eval or exec

From: Peter Otten <__pe...@web.de>
Tue, 09 Mar 2004 10:54:37 +0100
Oliver Kurz wrote:

> Hello,> > could someone give me a solution how to convert a string to a list without> using eval or exec?> > The string looks like:

[Python list containing nested lists and strings]

import compiler
import compiler.ast as ast

sample = '''[["abc1","abc2",["abc3","abc4"],"abc5"],
             ["abc6","abc7",["abc8","abc9"],
            ["abcA",["abcB","abcC"]],"abcD"],"abcE",
              1, 2.0, 3j]'''

node = compiler.parse(sample)
while not isinstance(node, ast.List):
    node = node.getChildNodes()[0]

def makeList(node):
    assert isinstance(node, ast.List)
    result = []
    for child in node.getChildNodes():
        try:
            result.append(child.value)
        except AttributeError:
            result.append(makeList(child))
    return result

assert makeList(node) == eval(sample)
print makeList(node)

Peter

Recent Messages in this Thread
Paul McGuire Mar 09, 2004 09:16 am
Peter Otten Mar 09, 2004 09:54 am
William Park Mar 09, 2004 04:59 pm
DomF Mar 10, 2004 12:02 pm
Peter Otten Mar 10, 2004 12:57 pm
Peter Harris Mar 11, 2004 10:28 pm
Messages in this thread