Solve the attributeerror str object has no attribute decode error

Today we will learn to troubleshoot a decode error that you will encounter when trying to decode a string in Python3.

Attributeerror: str object has no attribute decode in Python

This attribute error occurs because you are trying to call the decode() function on a Python string object, which is by default already decoded. The way to overcome this error, is simply use the string objects, without decoding it.

How to reproduce this error?

Assume that you have the following string:

lang_str = 'Python is one of the best languages to learn'

If we assume that the string is encoded to bytes and try to decode it, you receive the error message:

lang_str.decode()
AttributeError: 'str' object has no attribute 'decode'

Whereas if our string is encoded, then decoding it works just fine. Let’s take a quick look at an example.

# first, we encode the string
encoded_lang_str = lang_str.encode()
print ("The encoded string object type is : {}".format(type(encoded_lang_str)))
print("The encoded string: "  + str(encoded_lang_str))
print("The decoded string: " + encoded_lang_str.decode())

You’ll receive the following result:

The encoded string object type is: <class 'bytes'>
The encoded string: b'Python is one of the best languages to learn'
The decoded string: Python is one of the best languages to learn

Fixing the str object has no attribute decode error

In essence the best way to fix this error, is simply not to encode your Python 3 string objects.

Related learning

How to solve the bytes like object is required type error in Python?