Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to List without using eval() in Python

Tags:

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', '>=', 30] >> list position -[0] 
['age', '<', 36]  >> list position -[1]
like image 349
john Avatar asked Apr 06 '26 06:04

john


1 Answers

Try ast.literal_eval():

import ast
x = ast.literal_eval("[['age', '>=', 30], ['age', '<', 36]]")
print x
print type(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

like image 59
Impossibility Avatar answered Apr 08 '26 21:04

Impossibility



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!