Python String rpartition() Method split the given string into three parts. rpartition() starts looking for separator from the right side, till the separator is found and return a tuple which contains part of the string before separator, the separator and the part after the separator.
Python String rpartition() Method Syntax
Syntax : string.rpartition(separator)
Parameters :
- separator – separates the string at the first occurrence of it.
Return Value :
- It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string.
- It returns two empty strings, followed by the given string if the separator is not found in the string.
Example 1: Basic usage of Python String rpartition() Method
Here we are demonstrating the basic usages of Python String rpartition() Method
Python3
# String need to split string1 = "Geeks@for@Geeks@is@for@Lazyroar" string2 = "Ram is not eating but Mohan is eating" # Here '@' is a separator print (string1.rpartition( '@' )) # Here 'is' is separator print (string2.rpartition( 'is' )) |
Output :
('Geeks@for@Geeks@is@for', '@', 'Lazyroar') ('Ram is not eating but Mohan ', 'is', ' eating')
Example 2: Using rpartition() Method on String when separator is not present
Python String rpartition() Method returns first 2 arguments as empty String if separator is not present in String
Python3
# String need to split string = "Sita is going to school" # Here 'not' is a separator which is not # present in the given string print (string.rpartition( 'not' )) |
Output :
('', '', 'Sita is going to school')
Exceptions While Working With Python String rpartition()
TypeError: If a separator argument is not supplied, it will raise TypeError
Python3
# Python3 code explaining TypeError # in rpartition() string = "Bruce Waine is Batman" # Nothing is passed as separator print (string.rpartition()) |
Output :
Traceback (most recent call last): File "/home/e207c003f42055cf9697001645999d69.py", line 7, in print(str.rpartition()) TypeError: rpartition() takes exactly one argument (0 given)
ValueError: If the separator is an empty String, then rpartition() Method raises ValueError
Python3
string = "Bruce Waine is Batman" # Nothing is passed as separator print (string.rpartition("")) |
Output :
Traceback (most recent call last): File "/home/c8d9719625793f2c8948542159719007.py", line 7, in print(str.rpartition("")) ValueError: empty separator