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

PythonStringCastingBooleanConcatenation

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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 2 - Python

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 3 - Python

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

or

myvar = "the answer is %s" % answer

Solution 4 - Python

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.

Solution 5 - Python

answer = True

myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this

print(myvar)

Solution 6 - Python

answer = “Truemyvars = “the answer is” + answer

print(myvars)

That should give you the answer is True easily as you have stored answer as a string by using the quotation marks

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontravis1097View Question on Stackoverflow
Solution 1 - PythonAndrew GorcesterView Answer on Stackoverflow
Solution 2 - PythonwimView Answer on Stackoverflow
Solution 3 - PythonSquazicView Answer on Stackoverflow
Solution 4 - PythonBCArgView Answer on Stackoverflow
Solution 5 - PythonLijin G. VargheseView Answer on Stackoverflow
Solution 6 - Pythonuser13621326View Answer on Stackoverflow