How to Concatenate a Boolean to a String in Python?
































































5/5 - (1 vote)


Easy Solution



Use the addition + operator and the built-in str() function to concatenate a boolean to a string in Python. For example, the expression 'Be ' + str(True) yields 'Be True' .



s = 'Be ' + str(True)
print(s)
# Be True




The built-in str(boolean) function call converts the boolean to a string. The string concatenation + operator creates a new string by appending the “Boolean” string to another string.



What Can Go Wrong Without Conversion



If you try to concatenate the Boolean to a string without conversion using str() , Python will detect that you’re using the addition + operator with incompatible operand types and it raises a TypeError: can only concatenate str (not "bool") to str . Fix it by converting the Boolean to a string using str() .



Here’s the concatenation gone bad:



s = 'Be ' + True



The resulting error message:



Traceback (most recent call last):
File "C:UsersxcentDesktopcode.py", line 1, in <module>
s = 'Be ' + True
TypeError: can only concatenate str (not "bool") to str



And here’s how you can resolve this quickly and easily (as already shown):



s = 'Be ' + str(True)
print(s)
# Be True




Alternative: print()



Sometimes I see coders converting data types to string when they really only want to print the output. In these cases, consider the following more Pythonic solution rather than using string concatenation and conversion just to print a string along with a Boolean:



To print a string followed by a Boolean, pass both into the print() function, comma-separated. Python implicitly converts all comma-separated arguments to strings and prints them to the shell. In many cases, this is a far more elegant solution than explicitly using the string concatenation operator.



Here’s an easy example:



print('Be', True)
# Be True



The print() function also has many ways to customize the separator and end strings.




</div>
<div class=