Reputation: 1234
I'm trying to use eval function to read a string and evaluate the content that's inside the string.
a = 'red'
b = '=='
c = 'red'
print(eval(a+b+c))
it throw me an error
NameError: name 'red' is not defined
Note: i know it evaluate to red==red and read it as an variable instead of string but dont know how to make it string during eval process i.e 'red'=='red'
Than i tried with ast
import ast
ast.literal_eval(a+b+c)
but gives an error :
ValueError: malformed node or string: <_ast.Compare object at 0x035706F0>
Than i tried ast.parse
but i dont want to write seperate function/method based on operators
if it can be done with eval
only function/method
Any advice or links to useful resources would be appreciated.
Upvotes: 0
Views: 1016
Reputation: 114478
While what you are doing is a terrible idea and can be done in other ways, you need to add quotes within your string:
a = '\'red\''
b = ' == '
c = '\'red\''
OR
a = '"red"'
b = ' == '
c = '"red"'
OR
a = "'red'"
b = ' == '
c = "'red'"
Any of these should work. The choice is yours based on the type of quotes you want and the amount of escaping you are willing to do.
On a side note, you don't need to use eval
for your particular example:
a == c
will give the result of the eval. If you are worried about not knowing the operator, use a dict
and the operator
module:
import operator
ops = {
'==': operator.eq,
'<': operator.lt,
'<=': operator.le,
...
}
ops[b](a, c)
Upvotes: 2
Reputation: 3279
a = "'red'"
c = "'red'"
A more general way to do this is using repr
:
repr('red') # -> "'red'"
repr('"blue"') # -> '\'"blue"\'' (this does actually evaluate to '"blue"')
Upvotes: 1