I am receiving some rule from file and would like to prepare query at run time but getting following error. any input.
a = "AC"
cond = "startswith"
rule = "AC"
eval("%s.%s(%s)" %(a, cond, rule))
CodePudding user response:
If you must use eval
, use %r
in your format string when you want to substitute in strings, to get the repr
of the str
(including quotes) so they remain valid string literals, not raw names; as written, you're trying to run the code AC.startswith(AC)
, with %r
for first and third placeholder (eval("%r.%s(%r)" %(a, cond, rule))
) you'd be running "AC".startswith("AC")
.
CodePudding user response:
Try in this way:
eval(("'%s'.%s('%s')" %(a, cond, rule)))
You forgot single quotes to define strings in function evaluation