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

133,074

Solution 1

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

Solution 2

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

Solution 3

answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer

Solution 4

Using the so called f strings:

answer = True
myvar = f"the answer is {answer}"

Then if I do

print(myvar)

I will get:

the answer is True

I like f strings because one does not have to worry about the order in which the variables will appear in the printed text, which helps in case one has multiple variables to be printed as strings.

Share:
133,074
travis1097
Author by

travis1097

Updated on May 27, 2020

Comments

  • travis1097
    travis1097 almost 4 years

    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.

  • Makoto
    Makoto about 12 years
    The %s outside of quotes shouldn't be there, but this is indeed correct.
  • Joel
    Joel over 5 years
    Welcome to SO, Lijin G. Varghese! Code-only answers are discouraged here, as they provide no insight into how the problem was solved. Please update your answer with an explanation of how your code solves the problem at hand :)
  • cstrutton
    cstrutton almost 4 years
    But he doesn't have the answer stored as a string. It is a boolean. The question is how to convert a dynamic boolean to its string representation.