Python str.rpartition() function


In Python, the str.rpartition() method is similar to str.partition(), but it splits a string into three parts based on the last occurrence of a specified separator. This method is useful when you want to divide a string into sections while retaining the last occurrence of the separator.

Syntax

str.rpartition(separator)
  • separator: The string that you want to use as the delimiter to split the original string.

Return Value

The method returns a tuple with three elements:

  1. The part of the string before the last occurrence of the separator.
  2. The separator itself.
  3. The part of the string after the last occurrence of the separator.

If the separator is not found in the string, the first element of the tuple will be the original string, and the second and third elements will be empty strings.

Example Usage

  1. Basic usage:
text = "apple, banana, cherry" result = text.rpartition(", ") print(result) # Output: ('apple, banana', ', ', 'cherry')
  1. Separator not found:

If the separator is not present in the string, the entire string is returned as the first element of the tuple, with the other two elements being empty:

text = "Hello World!" result = text.rpartition(", ") print(result) # Output: ('Hello World!', '', '')
  1. Multiple occurrences of the separator:

The rpartition() method splits at the last occurrence of the separator:

text = "apple, banana, cherry, date" result = text.rpartition(", ") print(result) # Output: ('apple, banana, cherry', ', ', 'date')
  1. Using an empty separator:

If an empty string is passed as the separator, the behavior is similar to str.partition(), splitting between each character:

text = "abc" result = text.rpartition("") print(result) # Output: ('', '', 'abc') (empty before and after)

Summary

  • Use str.rpartition() to split a string into three parts based on the last occurrence of a specified separator.
  • It returns a tuple containing the part before the last occurrence of the separator, the separator itself, and the part after the separator.
  • If the separator is not found, the original string is returned as the first element, with the other two elements being empty strings.
  • This method is useful for scenarios where you want to extract content based on the last delimiter in a string, while keeping that delimiter as part of the result.