AttributeError: 'str' object has no attribute
What it means
You called a method that strings do not have. Often the variable holds a string when you expected a list or a dictionary, or the method name is misspelt. When Python can guess what you meant, it adds Did you mean: ...? to the message.
1. Using `append()` on a string
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> AttributeError: 'str' object has no attribute 'append'
The fix
Hello World
Strings have no append(): + or += joins them into a new string. To collect many pieces, append them to a list and finish with ''.join(pieces).
2. A misspelt method name
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> AttributeError: 'str' object has no attribute 'capitalise'. Did you mean: 'capitalize'?
The fix
Ana
Method names must be spelt exactly, in American spelling: capitalize, not capitalise. Python suggests the right name at the end of the message when it finds a close match.
3. JSON text that was never parsed
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> AttributeError: 'str' object has no attribute 'get'
The fix
Ana
Text read from a file or a web API is just a string until you parse it. json.loads() turns JSON text into a dictionary, which has a get() method.
When you see this error, check
- Print the variable and its
type(): a string may be sitting where you expected a list or a dictionary. - Read the
Did you meanhint when Python adds one. - Run
print(dir(''))to see every string method. - Remember that strings cannot change: methods return a new string, so write
text = text.strip().
Related errors
All Python errors · How to read a traceback · Step through your code