Last updated: Apr 20, 2022
Check out my new book
The Python "AttributeError: 'int' object has no attribute 'encode'" occurs
when we call the
encode() method on an integer. To solve the error, make sure
the value you are calling
encode on is of type string.
Here is an example of how the error occurs.
my_str = 'hello world' my_str = 123 # ⛔️ AttributeError: 'int' object has no attribute 'encode' print(my_str.encode('utf-8'))
We reassigned the
my_str variable to an integer and tried to call the
encode() method on the integer which caused the error.
print() the value you are calling
encode() on, it will be an integer.
To solve the error in the example, we would have to remove the reassignment or correct it.
my_str = 'hello world' print(my_str.encode('utf-8')) # 👉️ b'hello world'
If you are trying to get the encoded version of a number as a bytes object,
convert the integer to a string before calling
my_num = 1234 result = str(my_num).encode('utf-8') print(result) # 👉️ b'1234'
method returns an encoded version of the string as a bytes object. The default
You might also be assigning the result of calling a function that returns an integer to a variable.
def get_string(): return 100 my_string = get_string() # ⛔️ AttributeError: 'int' object has no attribute 'encode' print(my_string.encode('utf-8'))
my_string variable gets assigned to the result of calling the
The function returns an integer, so we aren't able to call
encode() on it.
To solve the error, you have to track down where the specific variable gets assigned an integer instead of a string and correct the assignment.