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

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


answer = Truemyvar = "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).


The recommended way is to let str.format handle the casting (docs). Methods with %s substitution may be deprecated eventually (see PEP3101).

>>> answer = True>>> myvar = "the answer is {}".format(answer)>>> print(myvar)the answer is True

In Python 3.6+ you may use literal string interpolation:

 >>> print(f"the answer is {answer}")the answer is True


answer = Truemyvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer