TypeError: can only concatenate str (not "bool") to str

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

TypeError: can only concatenate str (not "bool") to str #

The Python "TypeError: can only concatenate str (not "bool") to str" occurs when we try to concatenate a string and a boolean. To solve the error, convert the boolean to a string or use a formatted string literal.

typeerror can only concatenate str not bool to str

Here is an example of how the error occurs.

main.py
my_str = 'is subscribed: ' my_bool = True # ⛔️ TypeError: can only concatenate str (not "bool") to str print(my_str + my_bool)
We tried to use the addition (+) operator to concatenate a string and a boolean which caused the error.

The values on the left and right-hand sides need to be of compatible types.

If you only need to print the boolean, separate the string and the bool using a comma (not a +).

main.py
my_str = 'is subscribed: ' my_bool = True print(my_str, my_bool) # 👉️ is subscribed: True

Alternatively, you can convert the boolean to a string and concatenate the two strings.

main.py
my_str = 'is subscribed: ' my_bool = True result = my_str + str(my_bool) print(result) # 👉️ is subscribed: True

We passed the boolean to the str() class to convert it to a string, so we can concatenate the two strings.

An alternative to concatenating strings with the addition (+) operator is to use a formatted string literal.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_str = 'is subscribed:' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_bool = True print(type(my_bool)) # 👉️ <class 'bool'> print(isinstance(my_bool, bool)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 3,000 articles.