For example I have:
x = True and True
print x
I want to be able to do something like:
x = True and True
print "The answer to ", some_function(x), "is", x
Such that the program reads:
The answer to True and True is True.
Is there a some_function() that can read the content as a string instead of solving as a boolean?
Sorry in advance for any confusion on the wording of the question.
2 Answers 2
You can write it as a string:
x = 'True and True'
and evaluate it using eval:
print "The answer to ", x, "is", eval(x)
>>> x = 'True and True'
>>> print "The answer to ", x, "is", eval(x)
The answer to True and True is True
1 Comment
eval: it shouldn't be used on untrusted input. For example, if x is populated from a web service and the result is going into a log, the input must be sanitized (as much as possible) before running it through eval.What you're asking for is basically not possible in Python; expressions are evaluated immediately in Python and the interpreter does not "remember" what expression generated a particular value.
However, by changing your code slightly you can achieve a similar effect with eval:
expr = 'True and True'
print "The answer to", expr, "is", eval(expr)
As usual, with eval, never pass anything that you didn't write yourself (because it opens a security hole otherwise).
x = 'True and True'? In that case, look ateval().