How to Solve Python AttributeErrror: ‘str’ object has no attribute ‘remove’

by | Programming, Python, Tips

This error occurs when you try to call the remove() method on a string to remove one or more characters. You can solve the error by calling the replace() method on the string or by calling the remove() method on a string. For example,

my_str = 'fruits'

new_str = my_str.replace('s','')

This tutorial will go through the error in detail and how to solve it with code examples.


AttributeErrror: ‘str’ object has no attribute ‘remove’

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 “‘str’ object has no attribute ‘remove’” tells us that the string object we handle does not have the attribute remove().

remove() is a list method that removes the first occurrence of the specified element.

We can check if an attribute exists for an object using the dir() function. For example,

my_str = 'Python'

print(type(my_str))

print('remove' in dir(my_str))
<class 'str'>
False

We can see that remove() is not in the list of attributes for the str object.

Example

Let’s look at an example of trying to call the remove() method on a string.

# Create string with unwanted characters
 
my_str = 'ssfruits'

# Attempt to remove the unwanted 's' at the start of the string

new_str = my_str.remove('s')

print(new_str)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [3], in <cell line: 2>()
      1 my_str = 'ssfruits'
----> 2 new_str = my_str.remove('s')
      3 print(new_str)

AttributeError: 'str' object has no attribute 'remove'

The error occurs because remove() is not a string method in Python.

Solution

We can solve the error by calling the str.replace() method that returns a copy of the string with the replaced characters. The syntax of the replace() method is as follows:

string.replace(old_value, new_value, count)
  • old_value: Required. The string to search for
  • new_value: Required. The string to replace old_value with
  • count: Optional. A number specifying how many occurrences of old_value to replace. Default is all occurrences.

We can remove a character by setting the new_value to ''. Let’s remove the first two occurrences of the 's' character from the string. We want to keep the third occurrence of 's', so we will set count to 2

my_str = 'ssfruits'

new_str = my_str.replace('s', '', 2)

print(new_str)

Let’s run the code to get the result:

fruits

List Remove Method

If we want to remove the first occurrence of an element from a list, we can use the remove() method. For example,

my_lst = ['whale', 'lion', 'zebra', 'owl', 'platypus']

try:
    my_lst.remove('lion')
except ValueError:
    print('Item not in list')

print(my_lst)
['whale', 'zebra', 'owl', 'platypus']

Summary

Congratulations on reading to the end of this tutorial!

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

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