In Python, strings are immutable arrays of bytes representing Unicode characters. The pop()
method belongs to the List data type and removes the element at the specified position. If you try to call pop()
on a string, you will raise the AttributeError: ‘str’ object has no attribute ‘pop’.
To solve this error, you can convert a string to a list of individual characters using the split()
method then call the pop()
method on the resultant list.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
AttributeError: ‘str’ object has no attribute ‘pop’
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 ‘pop’” tells us that the string object does not have the attribute pop()
. The pop()
method belongs to the List data type and removes the element at the specified position. The syntax of the pop method is as follows:
list.pop(pos)
Parameters:
pos
: Optional. The index of the element to remove. Default is -1, which is the last element in the list.
Let’s look at an example of calling pop()
on a list:
lst = ["f", "u", "n", "!"] lst.pop() print(lst)
['f', 'u', 'n']
Example: Removing Last Character From String
Let’s look at an example of calling pop on a string; we will assign the result of calling pop()
to a new string variable called string2
. We need to define a new object because strings are immutable; we cannot change a string in-place like we can with a list.
string = "Pythonn" string2 = string.pop() print(string2)
Let’s run the code to see the result:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-6-e8b3441bfdd3> in <module> 1 string = "Pythonn" ----> 2 string2 = string.pop() 3 print(string2) AttributeError: 'str' object has no attribute 'pop'
We get the error because we call a list method pop()
on a string object.
Solution #1: Remove Last Element in String sing Slicing
To solve this error, we can use slicing to return a substring. We want to remove the last element in the string therefore we take a slice from the start of the string to the last character using string[:-1]
. Let’s look at the revised code:
string = "Pythonn" string = string[:-1] print('String with last character removed: ', string)
Let’s run the code to get the result:
String with last character removed: Python
Solution #2: Remove Element From String Using replace()
If we want to remove any other element in the string, you can use the replace method. The syntax of the replace() method is:
string.replace(old_value, new_value, count)
Parameters
old_value
: Required. The string to search for and replace.new_value
: Required. The string to replace the old value with.count
: Optiional. The number of occurrences of the old value to replace. Default is all occurrences.
Let’s look at the revised code:
string = "Pythonn" string = string.replace("o","") print('String with last character removed: ', string)
In the above code, we specify that we want to replace the character "o"
with an empty string ""
. Let’s run the code to see the result:
String with character removed: Pythnn
Solution #3: Remove Element From String Using re.sub()
If we want to remove any other element in the string, you can use the sub()
method from the regex library.
The syntax for the sub()
method is:
re.sub(chars_to_replace, chars_to_replace_with, str, occurrences)
We have to import the regex library in order to use the method. Let’s look at the revised code:
import re string = "Pythonn" string = re.sub("o", "", string) print('String with character removed: ', string)
In the above code, we specify that we want to replace the character "o"
with an empty string ""
. Let’s run the code to see the result:
String with last character removed: Pythnn
Example: Removing Last Word from Sentence
Let’s look at an example of a string holding several words separated by whitespace. We will try to call the pop method to remove the last word from the phrase. The code is as follows:
string = "Learning Python is really fun fun" string = string.pop() print('String with last word removed: ', string)
Let’s run the code to get the result:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-15-9df6d476c874> in <module> 1 string = "Learning Python is really fun fun" 2 ----> 3 string = string.pop() 4 5 print('String with last word removed: ', string) AttributeError: 'str' object has no attribute 'pop'
The error occurs because we call a list method pop() on a string object.
Solution
We can convert the string to a list of strings using the split() method to solve this error. Once we have the list, we can call the pop method. After updating the list, we can call the join() method to convert the list back to a string. Let’s look at the revised code:
string = "Learning Python is really fun fun" lst = string.split() print('List of words: ', lst) lst.pop() print('List of words with last word removed: ', lst) string = ' '.join(lst) print('String with last word removed: ', string)
Let’s run the code to see the result:
List of words: ['Learning', 'Python', 'is', 'really', 'fun', 'fun'] List of words with last word removed: ['Learning', 'Python', 'is', 'really', 'fun'] String with last word removed: Learning Python is really fun
We successfully split the string into a list of strings, removed the last element, and then joined the list back to a string.
Summary
Congratulations on reading to the end of this tutorial! The AttributeError: ‘str’ object has no attribute ‘pop’ occurs when you call the pop() method on a string object instead of a list. If you want to remove the last character in a string, you can use slicing. In other words,
string = string[:-1]
. If you have a string with sequences of characters separated by white space, you can use the split() method to convert the string to a list, then call the pop() method.
For further reading on AttributeErrors, go to the articles:
- How to Solve Python AttributeError: ‘list’ object has no attribute ‘join’.
- How to Solve Python AttributeError: ‘str’ object has no attribute ‘read’
- How to Solve Python AttributeError: ‘float’ object has no attribute ’round’
- How to Solve Python AttributeError: ‘str’ object has no attribute ‘strftime’
- How to Solve Python AttributeError: ‘list’ object has no attribute ‘copy’
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!
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.