How to Remove the Last Occurrence of a Substring from a String in Python?

Estimated read time 2 min read

To remove the last occurrence of a substring from a string in Python, you can use the rsplit() function to split the string at the last occurrence of the substring, and then join the remaining parts of the string using the join() function. Here is an example code snippet that removes the last occurrence of the substring “apple” from a string:

string_with_substring = "banana apple cherry apple dates apple"

# Remove last occurrence of substring "apple"
parts = string_with_substring.rsplit("apple", 1)
string_without_last_occurrence = "".join(parts)

print(string_without_last_occurrence)  # Output: banana apple cherry apple dates

In this code, we define a string that contains multiple occurrences of the substring “apple” (string_with_substring).

Next, we use the rsplit() function with a count of 1 to split the string at the last occurrence of the substring “apple”. This creates a list of two parts: the substring before the last occurrence of “apple”, and the substring after the last occurrence of “apple”.

Then, we use the join() function to join the two parts of the string back together without the last occurrence of the substring “apple”.

Finally, we print the modified string (string_without_last_occurrence) which does not contain the last occurrence of the substring “apple”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply