AttributeError: 'str' object has no attribute in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

AttributeError: 'str' object has no attribute in Python #

The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects. To solve the error, make sure the value is of the expected type before accessing the attribute.

attributeerror str object has no-attribute

Here is an example of how the error occurs.

main.py
my_str = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'my_attribute' print(my_str.my_attribute)

We tried to access an attribute that doesn't exist on string objects and got the error.

If you print() the value you are accessing the attribute on, it will be a string.

To solve the error, you need to track down where exactly you are setting the value to a string in your code and correct the assignment.

Another common cause of the error is misspelling a built-in method (method names are case-sensitive).

Make sure you aren't accessing a list at a specific index before calling a list-method.

main.py
my_list = ['a', 'b', 'c'] # ⛔️ AttributeError: 'str' object has no attribute 'append' my_list[2].append('d')

We accessed the list element at index 2, which is a string and called the append() method on the string which caused the error.

To solve the error, we have to call the append() method on the list.

main.py
my_list = ['a', 'b', 'c'] my_list.append('d') print(my_list) # 👉️ ['a', 'b', 'c', 'd']

Make sure you aren't reassigning the value of your variable somewhere in your code.

main.py
my_list = ['a', 'b', 'c'] # 👇️ list got reassigned to a string my_list = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'append' my_list.append('d')

We set the value of the my_list variable to a list initially, but we set it to a string later on, which caused the error.

Another common cause of the error is trying to call the decode() method on a string (already decoded) object.

main.py
my_str = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'? decoded = my_str.decode(enoding='utf-8')

To solve the error, remove the call to the decode() method, because if you have a string, it is already decoded.

The decode() method is used to decode a bytes object into a string.

If you are writing to or reading from a file, make sure you aren't calling the write() or read() methods on the filename.

main.py
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: # ⛔️ AttributeError: 'str' object has no attribute 'write' file_name.write('first line' + '\n') file_name.write('second line' + '\n') file_name.write('third line' + '\n')

The issue in the code sample is that we are calling the write() method on a string (the filename) whereas we should be calling it on the file object.

main.py
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')

If you need to check if a substring is in a string, use the in operator.

main.py
my_string = 'hello world' if 'hello' in my_string: # 👉️ this runs print('hello is contained in the string') else: print('hello is not contained in the string')

If you need to check whether an object contains an attribute, use the hasattr function.

main.py
my_string = 'hello world' if hasattr(my_string, 'upper'): print(my_string.upper()) else: print('Attribute is not present in object')

The hasattr function takes the following 2 parameters:

NameDescription
objectThe object we want to test for the existence of the attribute
nameThe name of the attribute to check for in the object

The hasattr() function returns True if the string is the name of one of the object's attributes, otherwise False is returned.

Using the hasattr function would handle the error if the attribute doesn't exist on the object, however you still have to figure out where the variable gets assigned a string in your code.

A good way to start debugging is to print(dir(your_object)) and see what attributes a string has.

Here is an example of what printing the attributes of a string looks like.

main.py
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: str object has no attribute error".

To solve the error, either convert the value to the correct type before accessing the attribute, or correct the type of the value you are assigning to the variable before accessing any attributes.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.