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.
- Don’t use the encode() method on bytes objects
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.