Bootstrap FreeKB - Python (Scripting) - Resolve "TypeError: cannot concatenate 'str' and 'bool' objects"
Python (Scripting) - Resolve "TypeError: cannot concatenate 'str' and 'bool' objects"

Updated:   |  Python (Scripting) articles

Let's say the following is being returned by your Python script.

TypeError: cannot concatenate 'str' and 'bool' objects

 

This occurs when attempting to do something with both a string and a boolean. For example, the following script would return the error.

#!/usr/bin/python
foo = True
print ("Hello " + foo)

 

type could be used to see the foo is a boolean and Hello is a string.

#!/usr/bin/python
foo = True
greeting = "Hello"
print(type(foo))
print(type(greeting))

 

Sometimes it makes sense to wrap the boolean inside of the str function. In this example, the error would no longer be returned and the script would print Hello True.

#!/usr/bin/python
foo = True
print ("Hello " + str(foo))

 

Or better yet, use Python3 f-string formatter.

#!/usr/bin/python3
foo = True
print (f"Hello {foo}")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a0ad6f in the box below so that we can be sure you are a human.