Python : Find and remove the last occurrence of specific string in python

python @ Freshers.in

To find and remove the last occurrence of a specific substring in a string, you can use the str.rfind() method to find the position of the last occurrence and then slice the string accordingly. Here’s a function that does this:

def remove_last_occurrence(text, substring):
    index = text.rfind(substring)
    
    if index == -1:  # substring not found
        return text
    
    # Remove the substring
    return text[:index] + text[index + len(substring):]

text = "I have a cat. The cat is cute. I love my cat."
substring = "cat"

result = remove_last_occurrence(text, substring)
print(result)

This script will output:

I have a cat. The cat is cute. I love my .

The last occurrence of the substring “cat” has been removed from the original string.

Refer more on python here :

Author: user

Leave a Reply