Editor

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

Broken
message = 'Hello'
message.append(' World')
print(message)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
AttributeError: 'str' object has no attribute 'append'

The fix

Fixed
message = 'Hello'
message += ' World' # strings join with +
print(message)
Output
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).

Try fixing it yourself in the editor

2. A misspelt method name

This raises the error

Broken
name = 'ana'
print(name.capitalise())
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
AttributeError: 'str' object has no attribute 'capitalise'. Did you mean: 'capitalize'?

The fix

Fixed
name = 'ana'
print(name.capitalize())
Output
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.

Try fixing it yourself in the editor

3. JSON text that was never parsed

This raises the error

Broken
data = '{"name": "Ana", "age": 31}'
print(data.get('name'))
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
AttributeError: 'str' object has no attribute 'get'

The fix

Fixed
import json
data = '{"name": "Ana", "age": 31}'
person = json.loads(data) # text becomes a dictionary
print(person.get('name'))
Output
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.

Try fixing it yourself in the editor

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 mean hint 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().

All Python errors · How to read a traceback · Step through your code