How to Solve Python AttributeError: ‘list’ object has no attribute ‘replace’

by | Programming, Python, Tips

In Python, the list data structure stores elements in sequential order. We can use the String replace() method to replace a specified string with another specified string. However, we cannot apply the replace() method to a list. If you try to use the replace() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘replace’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


AttributeError: ‘list’ object has no attribute ‘replace’

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 part “‘list’ object has no attribute ‘replace’” tells us that the list object we are handling does not have the replace attribute. We will raise this error if we try to call the replace() method on a list object. replace() is a string method that replaces a specified string with another specified string.

Python replace() Syntax

The syntax for the String method replace() is as follows:

string.replace(oldvalue, newvalue, count)

Parameters:

  • oldvalue: Required. The string value to search for within string
  • newvalue: Required. The string value to replace the old value
  • count: Optional. A number specifying how many times to replace the old value with the new value. The default is all occurrences

Let’s look at an example of calling the replace() method to remove leading white space from a string:

str_ = "the cat is on the table"

str_ = str.replace("cat", "dog")

print(str_)
the dog is on the table

Now we will see what happens if we try to use the replace() method on a list:

a_list = ["the cat is on the table"]

a_list = a_list.replace("cat", "dog")

print(a_list)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 a_list = ["the cat is on the table"]
      2 
----≻ 3 a_list = a_list.replace("cat", "dog")
      4 
      5 print(a_list)

AttributeError: 'list' object has no attribute 'replace'

The Python interpreter throws the Attribute error because the list object does not have replace() as an attribute.

Example #1: Using replace() on a List of Strings

Let’s look at an example list of strings containing descriptions of different cars. We want to use the replace() method to replace the phrase “car” with “bike”. Let’s look at the code:

lst = ["car one is red", "car two is blue", "car three is green"]

lst = lst.replace('car', 'bike')

print(lst)

Let’s run the code to get the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----≻ 1 lst = lst.replace('car', 'bike')

AttributeError: 'list' object has no attribute 'replace'

We can only call the replace() method on string objects. If we try to call replace() on a list, we will raise the AttributeError.

Solution

We can use list comprehension to iterate over each string and call the replace() method. Let’s look at the revised code:

lst = ["car one is red", "car two is blue", "car three is green"]

lst_repl = [i.replace('car', 'bike') for i in lst]

print(lst_repl)

List comprehension provides a concise, Pythonic way of accessing elements in a list and generating a new list based on a specified condition. In the above code, we create a new list of strings and replace every occurrence of “car” in each string with “bike”. Let’s run the code to get the result:

['bike one is red', 'bike two is blue', 'bike three is green']

Example #2: Using split() then replace()

A common source of the error is the use of the split() method on a string prior to using replace(). The split() method returns a list of strings, not a string. Therefore if you want to perform any string operations you will have to iterate over the items in the list. Let’s look at an example:

particles_str = "electron,proton,muon,cheese"

We have a string that stores four names separated by commas. Three of the names are correct particle names and the last one “cheese” is not. We want to split the string using the comma separator and then replace the name “cheese” with “neutron”. Let’s look at the implementation that will raise an AttributeError:

particles = str_.split(",")

particles = particles.replace("cheese", "neutron")

Let’s run the code to see the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----≻ 1 particles = particles.replace("cheese", "neutron")

AttributeError: 'list' object has no attribute 'replace'

The error occurs because particles is a list object, not a string object:

print(particles)
['electron', 'proton', 'muon', 'cheese']

Solution

We need to iterate over the items in the particles list and call the replace() method on each string to solve this error. Let’s look at the revised code:

particles = [i.replace("cheese","neutron") for i in particles]

print(particles)

In the above code, we create a new list of strings and replace every occurrence of “cheese” in each string with “neutron”. Let’s run the code to get the result:

['electron', 'proton', 'muon', 'neutron']

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘replace’” occurs when you try to use the replace() function to replace a string with another string on a list of strings.

The replace() function is suitable for string type objects. If you want to use the replace() method, ensure that you iterate over the items in the list of strings and call the replace method on each item. You can use list comprehension to access the items in the list.

Generally, check the type of object you are using before you call the replace() method.

For further reading on AttributeErrors involving the list object, go to the article:

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