Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

How to Find the Last Occurrence of a Substring in a Python String

Find a substring’s final index in Python with rfind(), handle missing matches with rindex(), and split around the last separator with rpartition().
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s str.rfind() to get the index of a substring’s final occurrence. It returns the highest matching index, or -1 if there is no match. Use str.rindex() instead if a missing match should raise ValueError.

Find the final match with rfind()

Call rfind(sub) on the string you want to search. The returned value is the zero-based index where the final match begins—not the number of matches.

text = "spam, spam, spam"
needle = "spam"

last_index = text.rfind(needle)
if last_index == -1:
    print("not found")
else:
    print(last_index)  # 12

In this example, the final "spam" begins at index 12. The Python 3.14.8 built-in types documentation describes rfind() as returning the highest index where the substring is found, or -1 when it is absent.

Choose between rfind() and rindex()

Both methods search for the final occurrence; the difference is how they handle a missing substring.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Method If a match exists If no match exists Use it when
rfind(sub) Returns the highest matching index. Returns -1. A missing match is an ordinary case you want to handle explicitly.
rindex(sub) Returns the highest matching index. Raises ValueError. A missing match should be treated as an error.

For example, if you choose rindex() but want to turn the exception into a value, catch it:

try:
    last_index = text.rindex(needle)
except ValueError:
    last_index = None

Limit the search to a range

rfind() and rindex() accept optional start and end arguments. These bounds follow slice-style interpretation, so you can search within a portion of the string:

text = "spam, spam, spam"
index = text.rfind("sp", 0, 10)
print(index)  # 6

The upper bound is handled like the end of a slice. See the official built-in types reference for the documented bounded-search behavior.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When you need the text around the last separator

If you want the portions before and after the final separator rather than its numeric position, use rpartition(sep). It returns a three-item tuple: the text before the last separator, the separator itself, and the text after it.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
path = "reports/2026/summary.txt"
before, separator, after = path.rpartition("/")
# before == "reports/2026"
# separator == "/"
# after == "summary.txt"

If the separator is not found, rpartition() returns ('', '', original_string). The method is documented in Python’s built-in types reference.

Common points to keep in mind

  • rfind() returns a string index, not a count of matches. str.count() answers a different question: it counts non-overlapping occurrences. For an empty substring, count() returns the string’s length plus one.
  • These methods operate on str text. If your input is bytes, use the corresponding bytes method or decode it before searching as text. Python documents the text and binary sequence methods in its built-in types reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.