String rpartition() Method in Python

Python String rpartition() Method

The rpartition() method is a built-in string method in Python. It is used to split a string into three parts based on the rightmost occurrence of a specified separator. The method returns a tuple containing three elements: the part before the separator, the separator itself, and the part after the separator.

The syntax of the rpartition() method is as follows:

string.rpartition(separator)

Here, string is the original string on which you want to perform the operation, and separator is the string that acts as the separator.

Let's see some examples to understand how it works:

Example 1:

text = "I love Python programming"
result = text.rpartition("love")
print(result)

Output:

('I ', 'love', ' Python programming')

In this example, the rpartition() method split the string at the rightmost occurrence of "love". The first element of the resulting tuple is the part of the string before "love", the second element is "love" itself, and the third element is the part of the string after "love".

Example 2:

path = "/home/user/documents/report.txt"
directory, separator, filename = path.rpartition("/")
print("Directory:", directory)
print("Separator:", separator)
print("Filename:", filename)

Output:

Directory: /home/user/documents
Separator: /
Filename: report.txt

In this example, we used rpartition() to split the file path based on the rightmost occurrence of the forward slash ("/"). The resulting tuple provides the directory, the separator itself (forward slash), and the filename.

Keep in mind that if the separator is not found in the original string, the method will return a tuple containing the original string as the first element, followed by two empty strings.