Python String rsplit() Method
The rsplit() method is used to split a string into a list of substrings starting from the right side.
Syntax
string.rsplit(separator, maxsplit)
Parameters
separator (Optional): The delimiter at which the string is split. If not specified, any whitespace (like spaces, tabs, or newlines) is used as a separator.
maxsplit (Optional): The maximum number of splits to perform. Default is -1 (no limit).
Return Value
Returns a list of substrings after splitting from the right.
Examples
Default Behavior (No Separator)
If you don’t provide a separator, the rsplit() method defaults to splitting the string at any whitespace character (like spaces, tabs, or newlines) from the right side.
Additionally, without a maxsplit argument, rsplit() method behaves the same as the split() method.
text = "apple banana mango"
fruits = text.rsplit()
print(fruits) # Output: ['apple', 'banana', 'mango']
With Separator
You can specify a character or a sequence of characters to act as a delimiter. Here is an example with a comma and a space as a delimiter:
text = "apple, banana, mango"
fruits = text.rsplit(", ")
print(fruits) # Output: ['apple', 'banana', 'mango']
With Multiple Characters
text = "appple#$banana#$mango"
fruits = text.rsplit("#$")
print(fruits) # Output: ['apple', 'banana', 'mango']
With maxsplit
The maxsplit parameter limits the number of splits from the right.
text = "apple, banana, mango"
fruits = text.rsplit(", ", 1)
print(fruits) # Output: ['apple, banana', 'mango']
Difference Between split() and rsplit()
The main difference between split() and rsplit() is:
The split() method splits the string from the left.
The rsplit() method splits the string from the right.