How to Solve Python AttributeError: ‘str’ object has no attribute ‘append’

by | Programming, Python, Tips

In Python, Strings are arrays of bytes representing Unicode characters. Although Strings are container type objects, like lists, you cannot append to a string. If you try to call the append() method on a string to add more characters, you will raise the error AttributeError: ‘str’ object has no attribute ‘append’.

To solve this error, you can use the concatenation operator + to add a string to another string.

This tutorial will go through how to solve this error, with the help of code examples.


AttributeError: ‘str’ object has no attribute ‘append’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. 

The attribute that does not exist in this case is “append”. We can use append on list objects, For example:

x = [1, 2, 3]
x.append(4)
print(x)
[1, 2, 3, 4]

However, if we try to append to a string, we will raise the Attribute error, for example:

string = "The dog"
new_string = string.append(" catches the ball")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 string = "The dog"
      2 
----≻ 3 new_string = string.append(" catches the ball")
AttributeError: 'str' object has no attribute 'append'

Example

Let’s look at an example where we have a list of strings. Each string is a name of a vegetable. We want to get the vegetable names that begin with c and print them to the console. The code is as follows:

vegetables = ["broccolli", "carrot", "courgette", "spinach", "beetroot", "cabbage", "asparagus", "cauliflower"]
veg_starting_with_c = ""
for veg in vegetables:
    if veg.startswith("c"):
        veg_starting_with_c.append(veg)
print(f'Vegetables starting with c: {veg_starting_with_c}')

We define a for loop to iterate over the strings in the list. We use the startswith() method to check if the string starts with c and then try to append the string to an empty string. Once the loop ends we try to print the completed string to the console.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      7     if veg.startswith("c"):
      8 
----≻ 9         veg_starting_with_c.append(veg)
     10 
     11 print(f'Vegetables starting with c: {veg_starting_with_c}')
AttributeError: 'str' object has no attribute 'append'

The error occurs because the variable veg_starting_with_c is a string, we cannot call the append() method on a string.

Solution #1

To solve this error, we can use the concatenation operator to add the strings to the empty string. Note that strings are immutable, so we need to create a new string variable each time we use the concatenation operator. Let’s look at the revised code:

vegetables = ["broccolli", "carrot", "courgette", "spinach", "beetroot",
cabbage", "asparagus", "cauliflower"]
veg_starting_with_c = ""
for veg in vegetables:
    if veg.startswith("c"):
        
        veg_starting_with_c = veg_starting_with_c + " " + veg
        
print(f'Vegetables starting with c: {veg_starting_with_c}')

Let’s run the code to get the result:

Vegetables starting with c:  carrot courgette cabbage cauliflower

Solution #2

Instead of concatenating strings, we can use a list and call the append method. Let’s look at the revised code:

vegetables = ["broccolli", "carrot", "courgette", "spinach", "beetroot","cabbage", "asparagus", "cauliflower"]
veg_starting_with_c = []
for veg in vegetables:
    if veg.startswith("c"):
        
        veg_starting_with_c.append(veg)
        
print(f"Vegetables starting with c: {' '.join(veg_starting_with_c)}")

We can use the join() method to convert the list to a string. Let’s run the code to get the result:

Vegetables starting with c: carrot courgette cabbage cauliflower

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors with string objects, go to the article:

How to Solve Python AttributeError: ‘str’ object has no attribute ‘trim’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee