rpartition(): Splitting from Right

The rpartition() function in Python splits a string into three parts based on the last occurrence of a specified separator. It is particularly useful for retrieving the last segment of a string after a known character.

Syntax

string.rpartition(separator)
- separator: The substring by which the string is split from the right. Three parts are here.

1. Left part of the matched string
2. The searched string
3. Right part of the matched string

If not found, `rpartition()` returns `('', '', original_string)`.
my_str='Welcome to Plus2net'
output=my_str.rpartition('to')
print(output)
Output is here
('Welcome ', 'to', ' Plus2net')
We can add one more line to display the last element
print(output[2])
Output
  plus2net
If matching string is not found then rpartition() returns the tuple with 3rd element as full string.
my_str='Welcome to Plus2net'
output=my_str.rpartition('ab')
print(output)
Output is here
('', '', 'Welcome to Plus2net')
If we use partition() in place or rpartition() the output is here ( the difference between rpartition() and partition() )
('Welcome to Plus2net', '', '')

Example 1: Basic Usage

text = "apple-orange-banana"
result = text.rpartition("-")
print(result)
Output:
('apple-orange', '-', 'banana')

Example 2: Separator Not Found

If the specified separator is absent, the entire string is returned as the third element.
text = "apple-orange-banana"
result = text.rpartition("/")
print(result)
Output:
('', '', 'apple-orange-banana')

Example 3: Extracting File Extension

Using rpartition() to separate the filename and extension.
filename = "document.pdf"
name, sep, extension = filename.rpartition(".")
print("Name:", name)
print("Extension:", extension)
Output:
Name: document
Extension: pdf

Applications of rpartition()

  • File Processing: Extract file extensions or last path segments.
  • String Parsing: Split strings by the last occurrence of a delimiter.
  • Data Cleaning: Retrieve trailing segments for analysis.

All String methods


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer