Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Matt Bennett
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.
Here is an example of how the error occurs.
my_bytes = b'hello ' my_str = 'world' # ⛔️ TypeError: can't concat str to bytes result = my_bytes + my_str
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_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.
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
.
Once you convert the bytes object to a string, you can use formatted string literals.
# 👇️ decode bytes object my_bytes = b'hello '.decode('utf-8') my_str = 'world' result = f'{my_bytes} {my_str}' print(result) # "hello world"
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.
# 👇️ 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.