Check boolean expression in python string

I have a boolean expression in a string. eg. 20 < 30. There is an easy way to analyze and evaluate this string so that it returns True(in this case).

ast.literal_eval("20 < 30") does not work.

+5
source share
3 answers
>>> eval("20<30")
True
+2
source

Is this a user-defined string or one that you define?

If this is the string you are creating, you can use eval( eval("20 < 30")), but if the string is specified by the user, you can sanitize it first ...

+2
source

ast.literal_eval ( ). " node Python: , , , , dicts, booleans None"., 20<30 , bool.

, literal_eval , eval, ..

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 things in a sentence try, exceptwill lead to input errors in the evaluation lhs,rhs.

0
source

All Articles