Explain Codes LogoExplain Codes Logo

Find index of last occurrence of a substring in a string

python
functions
best-practices
performance
Anton ShumikhinbyAnton Shumikhin·Feb 7, 2025
TLDR

For locating the last occurrence of a substring inside a string, use Python's rfind() method. It efficiently scans from the end to the start, rendering the highest index where the substring appears, or -1 if the substring is not found.

last_index = "some text to search".rfind("text") # Note for beginners: Index in Python starts from 0. print(last_index) # Output: 5

This zeros-in on the position of the final occurrence at lightning speed.

rfind vs rindex: Unveiling differences

While rfind() seems readily comprehensible, discerning its difference from rindex() could help. Both methods are used to find the last occurrence of a substring, with significant deviation only when the substring is absent.

rfind() is handy if you're unsure whether the substring exists at all, as it returns -1 signaling no match found, whereas rindex() erupts a ValueError—equivalent of adding videos of kittens into your error logs.

# When the substring is absent in rfind(), it returns -1 weedle_index = "hello".rfind("z") # Weedle is a Pokémon, it has no business in a hello string. print(weedle_index) # Output: -1 # rindex() with a substring that doesn't exist – this raises ValueError try: weedle_index = "hello".rindex("z") except ValueError as e: # Having a Pokémon in your error messages helps, try it. print(e) # Output: substring not found

Avoiding pitfalls: Edge cases and conflicting names

Handling multiple occurrences of the substring? rfind() and *rindex() lead the pack. Yet, ensure not to clash with their functionality by avoiding conflicting names. Also, it’s a shout-out time to edge cases! Always test with different inputs for coverage.

# Potential shadowing of 'rfind' function rfind = "some string".rfind("some") # It's like calling your dog, Dog. Confusing, right? # The correct usage without variable name conflict last_occurrence_index = "some string".rfind("some")

When you're doing reverse searches with multi-character substrings, reverse the substring too before dabbling with index(). This preserves the order of characters in the substring.

Beyond rfind() and rindex(), manual methods and regex approaches are there in your toolkit.

Manual search:

  1. Reverse the string and apply index().
  2. Measure the resulting index from the end of the original string.

Regex approach:

Join the re library to expand your horizons, especially handy for pattern matching.

import re def manual_search(string, substring): # Here, you become the detective searching for clues. reverse_index = string[::-1].index(substring[::-1]) return len(string) - reverse_index - len(substring) def regex_search(string, substring): # Regex to the rescue when the manual search feels too caveman. matches = list(re.finditer(substring, string)) if matches: return matches[-1].start() else: # No worries, not all efforts result in matches. Keep trying! return -1

Tools to use: Which one at what time?

rfind(): Quick and easy for straightforward cases with no twists. rindex(): Convenient when you need explicit error handling for tight control flows (and your love for ValueError). Regex: Unleash your skills when the substring matches a complex pattern.