The Python Oracle

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

This video explains
How do I concatenate a boolean to a string in Python?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
00:23 Accepted answer (Score 30)
00:54 Answer 2 (Score 138)
01:27 Answer 3 (Score 9)
01:40 Answer 4 (Score 3)
02:13 Thank you

--

Full question
https://stackoverflow.com/questions/1050...

Accepted answer links:
[docs]: http://docs.python.org/library/string.ht...
[PEP3101]: http://legacy.python.org/dev/peps/pep-31.../
[literal string interpolation]: https://www.python.org/dev/peps/pep-0498/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #casting #boolean #concatenation

#avk47



ANSWER 1

Score 141


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




ACCEPTED ANSWER

Score 30


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 3

Score 9


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

or

myvar = "the answer is %s" % answer



ANSWER 4

Score 3


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.