Python String rpartition() Method

Example

Search for the last occurrence of the word "bananas" and return a tuple containing three elements:

  • 1 - All content before the match
  • 2 - The match
  • 3 - All content after the match
txt = "I could eat bananas all day, bananas are my favorite fruit"
x = txt.rpartition("bananas")
print(x)

Run Instance

Definition and Usage

The rpartition() method searches for the last occurrence of the specified string and splits the string into a tuple containing three elements.

The first element contains the part of the string before the specified string.

The second element contains the specified string.

The third element contains the part of the string after the string.

Syntax

string.rpartition(value)

Parameter Value

Parameter Description
value Required. The string to be retrieved.

More Examples

Example

If the specified value is not found, the rpartition() method will return a tuple containing: 1 - the entire string, 2 - an empty string, 3 - an empty string:

txt = "I could eat bananas all day, bananas are my favorite fruit"
x = txt.rpartition("apples")
print(x)

Run Instance