TypeError: decoding str is not supported in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
2 min

banner

# 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 is an example of how the error occurs.

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

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

# Make sure to supply 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}.

# You don't have to decode strings

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

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.

Encoding is the process of converting a 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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.