2

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]
1
  • 2
    "not allow to import" Is that a limitation imposed by a homework assignment or from a tool you're trying to use (like some scriptable application that wants a python script?). Either way, please update your question to reflect your exact requirements. Commented Oct 17, 2013 at 18:12

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Impossibility,
Thanks Impossibility, based on our application we can't used python regex and ast features. Because of our application not allow to import any classes as well as not allow to write function. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.