Last Updated : 05 Jan, 2025
String rpartition()
method in Python is a powerful tool for splitting a string into three parts, based on the last occurrence of a specified separator. It provides an efficient way to handle text parsing when we want to divide strings from the rightmost delimiter.
Let us start with a simple example:
Python
s = "welcome to Python programming"
# Using rpartition to split from the last occurrence of the space character
res = s.rpartition(" ")
print(res)
('welcome to Python', ' ', 'programming')
Explanation
'
is split into three parts: the part before the last space, the space itself, and the part after the space.Parameters
string.rpartition(separator)
(part_before, separator, part_after)
.(' ', ' ', original_string)
.The rpartition()
method can be handy when we want to isolate the last segment of a sentence. For instance, separating the last word of a sentence for further processing
s = "Data Science and Machine Learning"
# Splitting from the last occurrence of space
res = s.rpartition(" ")
print(res)
('Data Science and Machine', ' ', 'Learning')
Explanation
Sometimes, the separator we specify may not exist in the string. In such cases, the method returns the entire string as the last element in the tuple.
Python
s = "NoSeparatorHere"
# Attempting to split with a separator not present in the string
res = s.rpartition("-")
print(res)
('', '', 'NoSeparatorHere')
Explanation
The rpartition() method is particularly useful for splitting structured data like dates or timestamps. For instance, it can help isolate the day from a date string.
Python
s = "2024-12-27"
# Splitting the date string from the last occurrence of '-'
res = s.rpartition("-")
print(res)
('2024-12', '-', '27')
Explanation
'-'
character.The rpartition() method is often combined with other operations.
Python
s = "path/to/the/file.txt"
# Extracting the directory and filename
directory, separator, filename = s.rpartition("/")
print("Directory:", directory)
print("Filename:", filename)
Directory: path/to/the Filename: file.txt
Explanation
rpartition()
method in real-world scenarios like file manipulation or directory navigation.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4