Python String | rpartition()

rpartition() function in Python split the given string into three parts. rpartition() start looking for separator from right side, till the separator is found and return a tuple which contains part of the string before separator, argument of the string and the part after the separator.

Syntax :

string.rpartition(separator)

Parameters :

separator -  separates the string at the first occurrence of it.

Return Value :

  1. 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.
  2. It returns two empty strings, followed by the given string if the separator is not found in the string.

Exception :

If separator argument is not supplied, it will throw TypeError.

 

Code #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code explaining rpartition()
  
# String need to split
string1 = "Geeks@for@Geeks@is@for@geeks"
  
string2 = "Ram is not eating but Mohan is eating"
  
# Here '@' is a separator
print(string1.rpartition('@'))
  
# Here 'is' is seperator
print(string2.rpartition('is'))

chevron_right


Output :

('Geeks@for@Geeks@is@for', '@', 'geeks')
('Ram is not eating but Mohan ', 'is', ' eating')

 
Code #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code explaining rpartition()
  
# 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'))

chevron_right


Output :

('', '', 'Sita is going to school')

 
Code #3 : TypeError

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code explaining TypeError
# in rpartition()
  
str = "Bruce Waine is Batman"
  
# Nothing is passed as separator
print(str.rpartition())

chevron_right


Output :

Traceback (most recent call last):
  File "/home/e207c003f42055cf9697001645999d69.py", line 7, in 
    print(str.rpartition())
TypeError: rpartition() takes exactly one argument (0 given)

 
Code #4 : ValueError

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code explaining ValueError
# in rpartition()
  
str = "Bruce Waine is Batman"
  
# Nothing is passed as separator
print(str.rpartition(""))

chevron_right


Output :

Traceback (most recent call last):
  File "/home/c8d9719625793f2c8948542159719007.py", line 7, in 
    print(str.rpartition(""))
ValueError: empty separator


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.