Solve - TypeError: can't concat str to bytes in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Matt Bennett

Solve - TypeError: can't concat str to bytes in Python #

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

typeerror cant concat str to bytes

Here is an example of how the error occurs.

main.py
my_bytes = b'hello ' my_str = 'world' # ⛔️ TypeError: can't concat str to bytes result = my_bytes + my_str
We tried to use the addition (+) operator to concatenate a bytes object and a string 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_bytes = b'hello ' my_str = 'world' # 👇️ decode bytes object result = my_bytes.decode('utf-8') + my_str print(result) # 👉️ "hello world"

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_bytes = b'hello ' my_str = 'world' result = my_bytes + my_str.encode('utf-8') print(result) # 👉️ b"hello world"

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
# 👇️ decode bytes object my_bytes = b'hello '.decode('utf-8') my_str = 'world' result = f'{my_bytes} {my_str}' print(result) # "hello world"
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
# 👇️ decode bytes object my_bytes = b'hello ' print(type(my_bytes)) # 👉️ <class 'bytes'> print(isinstance(my_bytes, bytes)) # 👉️ True my_str = 'world' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ 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 1,000 articles.