Reputation: 16029
I have a boolean expression in a string. eg. 20 < 30
. Is there a simple way to parse and evaluate this string so it will return True
(in this case).
ast.literal_eval("20 < 30")
does not work.
Upvotes: 5
Views: 1733
Reputation: 88248
ast.literal_eval
shouldn't work since (from the docs) "The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.". The expression 20<30
requires some kind of evaluation, before it returns a bool
.
A safer suggestion would be to split the string on the operator and literal_eval
each side before passing to eval
, ie.
import ast
expr = "20 < 30"
operator = "<"
lhs,rhs = map(ast.literal_eval, map(str.strip, expr.split(operator)))
eval("%s %s %s"%(lhs,operator,rhs))
Wrapping the thing in a try, except
clause will catch some input errors when evaluating lhs,rhs
.
Upvotes: 0
Reputation: 1601
Is this a user-defined string, or one you're defining?
If it's a string you're creating, you could use eval
(eval("20 < 30")
), but if the string is given by the user, you might want to sanitize it first...
Upvotes: 2