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