Skip to content Skip to sidebar Skip to footer

How To Convert String To List Without Using Eval() In Python

I will like to convert the following string to a list without using eval in python. '[['age', '>=', 30], ['age', '<', 36]]' The output should be like this: ['age', '>=',

Solution 1:

Try ast.literal_eval():

import ast
x = ast.literal_eval("[['age', '>=', 30], ['age', '<', 36]]")
print x
printtype(x)

Running this script displays:

[['age', '>=', 30], ['age', '<', 36]]
<type'list'>

The ast.literal_eval() is a a safe eval() that only evaluates literals such as strings, lists, tuples, numbers, and booleans.

Source: http://docs.python.org/dev/library/ast.html#ast.literal_eval

Post a Comment for "How To Convert String To List Without Using Eval() In Python"