Solve - TypeError: decoding str is not supported in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Solve - TypeError: decoding str is not supported in Python #

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.

typeerror decoding str is not supported

Here are 2 examples of how the error occurs.

main.py
# ⛔️ 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.

main.py
print(str(b'abc', encoding='utf-8')) # 👉️ "abc"

If you need to concatenate strings, use the addition (+) operator.

main.py
print('abc' + str(123)) # 👉️ "abc123"

The addition (+) operator can be used to concatenate strings.

Alternatively, you can use a formatted string literal.

main.py
str_1 = 'abc' num_1 = 123 result = f'{str_1} {num_1}' print(result) # 👉️ 'abc 123'
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}.

The "TypeError: decoding str is not supported" error message means that we are somehow trying to decode a str.

Since the string has already been decoded from a bytes object, you need to remove any code that tries to decode it.

Here is a simple example of encoding a string to bytes and decoding the bytes object back to a string.

main.py
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.