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)
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)
<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')
b'appdividend.com' It is already encoded
To avoid the error, ensure you call the encode() method on a string, not a bytes object.