Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.rpartition() method

Reference for Python str.rpartition(): split a string at the last occurrence of a separator into a 3-tuple, with the not-found case and file path examples.

The str.rpartition() method searches from the right for a separator and returns a tuple of three strings: everything before the last occurrence, the separator, and everything after it. It is the right-hand twin of partition().

If the separator is missing, the tuple is two empty strings followed by the whole string, which is the opposite arrangement from partition(). The result always has three items, so unpacking is safe.

Python
print("a/b/c.txt".rpartition("/"))   # ('a/b', '/', 'c.txt')

Try it

Python Splitting at the last separator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python When the separator is missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.rpartition(sep)
Name Description
sep The separator to search for, from the right. It must not be empty.

Return value: a tuple (before, sep, after) for the last match, or ("", "", original_string) if sep is not found.

Raises: ValueError ("empty separator") if sep is empty; TypeError if it is not a string.

Usage notes

  • The leftover goes last when nothing matches. After rpartition() the original string is the third item, after partition() the first. Mixing them up is the most common bug.
  • Check the middle item to know whether the separator was found: it is empty on a miss.
  • Exactly one split, at the last occurrence. For several splits from the right use rsplit() with maxsplit.
  • Good for extensions and last path parts, though pathlib and os.path understand platform rules (os.path.splitext, Path.suffix).
  • Literal separator only, not a pattern.
  • Also on bytes and bytearray.