Python String rsplit()
Method
The rsplit() method in Python is used to split a string from the right. It returns a list of substrings, just like split()
, but starts splitting from the end of the string.
Syntax
string.rsplit([separator[, maxsplit]])
Parameters:
separator
(optional): The delimiter on which to split the string. If not provided, any whitespace is considered as the separator.maxsplit
(optional): Maximum number of splits. The splitting starts from the right.
Returns:
- A list of strings after splitting.
Example 1: Basic Usage of rsplit()
text = "apple,banana,cherry"
result = text.rsplit(",")
print(result)
['apple', 'banana', 'cherry']
Example 2: Using maxsplit
text = "apple,banana,cherry"
result = text.rsplit(",", 1)
print(result)
['apple,banana', 'cherry']
Here, only 1 split is done, and it starts from the right.
Example 3: Without Separator (Splits on Whitespace)
text = "Python is beginner friendly"
result = text.rsplit()
print(result)
['Python', 'is', 'beginner', 'friendly']
Key Differences: split()
vs rsplit()
split()
splits from the left (start).rsplit()
splits from the right (end).- Both accept the same parameters and return a list.
Use Cases
- When you only want to split the last few items in a string.
- Parsing file paths, logs, or reversed values.
Common Mistakes
- Forgetting that
maxsplit
works from the right. - Expecting
rsplit()
to modify the string (it returns a new list).
Practice Problem
Split the string "2025-05-14"
into day, month, and year using rsplit("-", 1)
. What will be the result?
date = "2025-05-14"
print(date.rsplit("-", 1))
Expected Output:
['2025-05', '14']
Summary
rsplit()
splits a string into a list, starting from the right.- Use
maxsplit
to control how many splits you want. - If no separator is given, whitespace is used.