Last updated: Apr 8, 2024
Reading time·2 min
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 is an example of how the error occurs.
# ⛔️ TypeError: decoding str is not supported str('hello', str(123))
The code sample has two calls to the str class, one nested inside the other.
Here is another example.
# ⛔️ TypeError: decoding str is not supported str('abc', encoding='utf-8')
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 string.
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
.
string
to a bytes
object and decoding is the process of converting a bytes
object to a string
.The bytes.decode() method returns a
string decoded from the given bytes. The default encoding is utf-8
.
Decoding is the process of converting a bytes
object to a string and since we
already have a string, we don't have to call the decode()
method on it.
You can learn more about the related topics by checking out the following tutorials: