How to Fix AttributeError: ‘bytes’ object has no attribute ‘encode’

'bytes' object has no attribute 'encode'

AttributeError: ‘bytes’ object has no attribute ‘encode'” error occurs when you are trying to “call the encode() method on a bytes object but it is already encoded.”

Reproduce the error

s = "Hello"

b = s.encode("utf-8") 
b.encode("utf-8")
print(b)

Output

AttributeError: 'bytes' object has no attribute 'encode'

How to fix it?

Here are two ways to fix the AttributeError: ‘bytes’ object has no attribute ‘encode’ error.

  1. Don’t use the encode() method on bytes objects
  2. Checking the type before calling encode()

Fix 1: Don’t use the encode() method on bytes objects

If the string is already encoded, don’t use the encode() method on the bytes object.

s = "Hello"

b = s.encode("utf-8") 
print(type(b))
print(b)

Output

<class 'bytes'>
b'Hello'

Fix 2: Checking the type of a variable

An alternative approach is to check the variable type before you call the encode() method.

def encode(string):
  if isinstance(string, str):
    encoded = string.encode('utf-8')
    return encoded
  else:
    print("It is already encoded")


result = encode('appdividend.com')
print(result)

result = encode(b'appdividend.com')

Output

b'appdividend.com'
It is already encoded

Conclusion

To avoid the error, ensure you call the encode() method on a string, not a bytes object.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.