0

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.

Ayush
  • 41,754
  • 51
  • 164
  • 239
J Bauer
  • 11
  • 1
  • 5
  • You mean you have a Python expression stored as a string? Like `x = 'True and True'`? In that case, look at `eval()`. – John Gordon Feb 17 '16 at 19:09

2 Answers2

1

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
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • It may be worth adding the usual warning about `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`. – skrrgwasme Feb 17 '16 at 19:14
0

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).

nneonneo
  • 171,345
  • 36
  • 312
  • 383