Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
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.
Here is an example of how the error occurs.
my_str = 'hello ' my_bytes = b'James Doe' # ⛔️ TypeError: can only concatenate str (not "bytes") to str result = my_str + my_bytes
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.
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.
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
.
Once you convert the bytes object to a string, you can use formatted string literals.
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"
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.
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.