A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-string-rpartition/ below:

Python String rpartition() Method - GeeksforGeeks

Python String rpartition() Method

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) 

Output
('welcome to Python', ' ', 'programming')

Explanation

Syntax of rpartition() method

string.rpartition(separator)

Parameters Return Type Examples of rpartition() method 1. Splitting using a space separator

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

Python
s = "Data Science and Machine Learning"

# Splitting from the last occurrence of space
res = s.rpartition(" ")

print(res) 

Output
('Data Science and Machine', ' ', 'Learning')

Explanation

2. When the separator is not found

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)  

Output
('', '', 'NoSeparatorHere')

Explanation

3. Using a specific character as the separator

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)  

Output
('2024-12', '-', '27')

Explanation

4. Combining rpartition() with other methods

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)    

Output
Directory: path/to/the
Filename: file.txt

Explanation



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