Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: decoding str is not supported" occurs when we try to
convert an object to a string multiple times or set the encoding
keyword
argument in our call to the str()
class without providing a bytes object.
Here are 2 examples of how the error occurs.
# ⛔️ TypeError: decoding str is not supported str('hello', str(123)) # ⛔️ TypeError: decoding str is not supported str('abc', encoding='utf-8')
The first example has two calls to the str
class, one nested inside the other.
In the second example, we set the encoding
keyword argument without providing
a valid bytes object.
We can only set the encoding when passing a valid bytes
object.
print(str(b'abc', encoding='utf-8')) # 👉️ "abc"
If you need to concatenate strings, use the addition (+) operator.
print('abc' + str(123)) # 👉️ "abc123"
The addition (+) operator can be used to concatenate strings.
Alternatively, you can use a formatted string literal.
str_1 = 'abc' num_1 = 123 result = f'{str_1} {num_1}' print(result) # 👉️ 'abc 123'
f
.Make sure to wrap expressions in curly braces - {expression}
.
The "TypeError: decoding str is not supported" error message means that we are
somehow trying to decode a str
.
Here is a simple example of encoding a string to bytes and decoding the bytes object back to a string.
my_bytes = 'hello world'.encode('utf-8') print(my_bytes) # 👉️ b'hello world' my_str = my_bytes.decode('utf-8') print(my_str) # 👉️ "hello world"
The str.encode
method returns an encoded version of the string as a bytes object. The default
encoding is utf-8
.
The bytes.decode
method returns a string decoded from the given bytes. The default encoding is
utf-8
.