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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "TypeError: can only concatenate str (not "bytes") to str" occurs when we try to concatenate a string and a bytes object. To solve the error, decode the bytes object into a string before concatenating the strings.

typeerror can only concatenate str not bytes to str

Here is an example of how the error occurs.

main.py
my_str = 'hello ' my_bytes = b'James Doe' # ⛔️ TypeError: can only concatenate str (not "bytes") to str result = my_str + my_bytes
We tried to use the addition (+) operator to concatenate a string and a bytes object which caused the error.

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

One way to solve the error is to convert the bytes object to a string.

main.py
my_str = 'hello ' my_bytes = b'James Doe' result = my_str + my_bytes.decode('utf-8') print(result) # 👉️ 'hello James Doe'

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8.

Alternatively, you can encode the string to a bytes object.

main.py
my_str = 'hello ' my_bytes = b'James Doe' result = my_str.encode('utf-8') + my_bytes print(result) # 👉️ b'hello James Doe'

The str.encode method returns an encoded version of the string as a bytes object. The default encoding is utf-8.

Either way, you have to make sure that the values on the left and right-hand side of the addition (+) operator are of compatible types (e.g. two strings).

Once you convert the bytes object to a string, you can use formatted string literals.

main.py
my_str = 'hello' # 👇️ decode bytes to str my_bytes = b'James Doe'.decode('utf-8') result = f'{my_str} {my_bytes}' print(result) # 👉️ "hello James Doe"
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 = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_bytes = b'James Doe' print(type(my_bytes)) # 👉️ <class 'bytes'> print(isinstance(my_bytes, bytes)) # 👉️ 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.