Straightforward Answer
Use the addition +
operator and the built-in str()
operate to concatenate a boolean to a string in Python. For instance, the expression 'Be ' + str(True)
yields 'Be True'
.
s="Be " + str(True) print(s) # Be True
- The built-in
str(boolean)
operate name converts theboolean
to a string. - The string concatenation + operator creates a brand new string by appending the “Boolean” string to a different string.
What Can Go Incorrect With out Conversion
In case you attempt to concatenate the Boolean to a string with out conversion utilizing str()
, Python will detect that you simply’re utilizing the addition +
operator with incompatible operand sorts and it raises a TypeError: can solely concatenate str (not "bool") to str
. Repair it by changing the Boolean to a string utilizing str()
.
Right here’s the concatenation gone dangerous:
s="Be " + True
The ensuing error message:
Traceback (most up-to-date name final): File "C:UsersxcentDesktopcode.py", line 1, in <module> s="Be " + True TypeError: can solely concatenate str (not "bool") to str
And right here’s how one can resolve this rapidly and simply (as already proven):
s="Be " + str(True) print(s) # Be True
Various: print()
You may go a number of differing types into the print()
operate, comma-separated. Python implicitly converts all values to strings and prints them to the shell. In lots of circumstances, it is a way more elegant resolution than explicitly utilizing the string concatenation operator.
Right here’s a straightforward instance:
print('Be', True) # Be True
The print()
operate additionally has some ways to customise the separator and finish strings.
👉 Really useful Tutorial: Understanding Python print()
Thanks for studying by means of the tutorial with us. ❤️ Love having you right here!
Whereas working as a researcher in distributed methods, Dr. Christian Mayer discovered his love for instructing pc science college students.
To assist college students attain greater ranges of Python success, he based the programming training web site Finxter.com. He’s creator of the favored programming ebook Python One-Liners (NoStarch 2020), coauthor of the Espresso Break Python sequence of self-published books, pc science fanatic, freelancer, and proprietor of one of many prime 10 largest Python blogs worldwide.
His passions are writing, studying, and coding. However his best ardour is to serve aspiring coders by means of Finxter and assist them to spice up their expertise. You may be part of his free electronic mail academy right here.