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
42.5k52 gold badges170 silver badges244 bronze badges
asked Feb 17, 2016 at 19:07
1
  • You mean you have a Python expression stored as a string? Like x = 'True and True'? In that case, look at eval(). Commented Feb 17, 2016 at 19:09

2 Answers 2

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
answered Feb 17, 2016 at 19:10
Sign up to request clarification or add additional context in comments.

1 Comment

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

answered Feb 17, 2016 at 19:13

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.