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:
lang_lst = ['Python', 'Go', 'JavaScript', 'R', 'Julia']
lang_lst.encode()
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:
[[b'Python', b'Go', b'JavaScript', b'R', b'Julia']]
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:
'Python, Go, JavaScript, R, Julia'
We can easily encode the string:
lang_str.encode('UTF-8')
This will return an encoded bytes object. You are able to decode your string using the decode() methods made available in the standard library.
Suggested learning
Fix the a bytes data is required typeerror excepting in Python 3