This attributeerror exception occurs when you try to access the encode method, which is available for Python strings; from a list or other iterables such as a dictionary, range or set. In today’s Python Automation tutorial, we will learn how to fix this issue in your integrated development environment of choice (PyCharm, Jupyter, VS Code).
Reproducing the attributeerror exception
Assume you have created the following Python list, which we would like to encode. You use the dot notation to call the encode method directly from your list / array:
This will throw the following exception and stop the execution of our Python program:
AttributeError: 'list' object has no attribute 'encode'
Here’s the error screenshot on my Jupyter Lab notebook:
Fixing the attributeerror encode for lists
We can use a simple list comprehension technique to convert each of our list elements to bytes. Foe example:
encoded_lst = [ [e.encode('UTF-8') for e in lang_lst]]
If we fetch our newly created lists we’ll see that each element was encoded to bytes:
Another option would be to convert our list to string and then go ahead and encode that string object into a bytes object.
lang_str = ', '.join(lang_lst) print(lang_str)
This will render the following string:
We can easily encode the string:
This will return an encoded bytes object. You are able to decode your string using the decode() methods made available in the standard library.