Python rpartition

Python rpartition function is used to partition the given string using the specified separator and return a tuple with three arguments.

This Python rpartition function starts looking for the separator from the Right-Hand side. Once it finds the separator, it returns the string before the Separator as Tuple Item 1, Separator itself as Tuple Item 2, and the sentence after the Separator (or remaining string) as Tuple Item 3. This section discusses how to write rpartition in this Programming with an example.

Python rpartition Syntax

The syntax of the string rpartition in Python Programming Language is


Separator: This argument is required, and if you forget this argument, it throws TypeError. If you pass the non-existing item as the separator, then the Python rpartition function returns two empty strings as Tuple Item 1, and Item 2, followed by the whole string as Tuple Item 3.

Return Value: The rpartition returns Tuple with three arguments. For example, If we have A*B*C and If we use * as a separator, it searches for * from right to left. Once it finds the * symbol, it returns the string before the * symbol as Tuple Item 1 (A*B), * as Tuple Item 2. And the remaining string is Tuple Item 3 (C).

TIP: Even though there are multiple occurrences of the separator, then it looks for the first occurrence from the right side.

Python rpartition Function Example

The following set of examples helps to understand the rpartition Function.

Str1 = 'Tutorial Gateway Website'
Str2 = 'Free-Tutorials-On-Python-Language'
Str3 = ''
Str4 = Str1.rpartition(' ')
print("Right Partitioning String 1 = ", Str4)

Str5 = Str2.rpartition('-')
print("Right Partitioning String 2 = ", Str5)

Str6 = Str3.rpartition('@')
print("Right Partitioning String 3 = ", Str6)

#Performing directly
Str7 = 'Python.Images.png'.rpartition('.')
print("Right Partitioning String 7 = ", Str7)

# Non Existing Item
Str8 = 'Tutorial Gateway'.rpartition('@')
print("Right Partitioning String 8 = ", Str8)
Python RPartition string Method

The following Python rpartition statement partitions the Str1 into multiple parts based on the specified separator. That is Empty Space and prints the output.

Str4 = Str1.rpartition(' ')

It partitions the Str2 into multiple parts based on the ‘-‘ symbol and prints the output.

Str5 = Str2.rpartition('-')

The following statement partition the Str3 string into multiple parts based on the ‘@’ symbol and prints the output.

Str6 = Str3.rpartition('@')

Here, we used the Python rpartition function directly on the string text.

Str7 = 'Python.Images.png'.rpartition('.')

The below Python statement looks for @, which doesn’t exist. So, it returns the Tuple as (”, ”, ‘Tutorial Gateway’)

Str8 = 'Tutorial Gateway'.rpartition('@')

TIP: Refer to partition in String Methods, which performs the same operation but from left to right.