How do I concatenate a boolean to a string in Python?

travis1097 picture travis1097 · May 9, 2012 · Viewed 119.3k times · Source

I want to accomplish the following

answer = True
myvar = "the answer is " + answer

and have myvar's value be "the answer is True". I'm pretty sure you can do this in Java.

Answer

Andrew Gorcester picture Andrew Gorcester · May 9, 2012
answer = True
myvar = "the answer is " + str(answer)

Python does not do implicit casting, as implicit casting can mask critical logic errors. Just cast answer to a string itself to get its string representation ("True"), or use string formatting like so:

myvar = "the answer is %s" % answer

Note that answer must be set to True (capitalization is important).