Splits a string into a list of substrings, starting from the right
Usage
The rsplit()
method splits the string on a specified delimiter and returns the list of substrings.
When you specify maxsplit, only the given number of splits will be made.
Syntax
string.rsplit(delimiter,maxsplit)
Parameter | Condition | Description |
delimiter | Optional | Any character to split the sting with. Default is whitespace. |
maxsplit | Optional | A number specifying how many splits to make. Default value is -1 (no limit on splits) |
Split on Whitespace
When delimiter is not specified, the string is split on whitespace.
S = 'The World is Beautiful'
x = S.rsplit()
print(x)
# Prints ['The', 'World', 'is', 'Beautiful']
Split on a Delimiter
You can split a string by specifying a delimiter.
# Split on comma
S = 'red,green,blue'
x = S.rsplit(',')
print(x)
# Prints ['red', 'green', 'blue']
# Delimiter with multiple characters
S = 'the beginning is the end is the beginning'
x = S.rsplit(' is ')
print(x)
# Prints ['the beginning', 'the end', 'the beginning']
Limit Splits With Maxsplit
When you specify maxsplit, only the given number of splits will be made, starting from the right. The resulting list will have the specified number of elements plus one.
S = 'The World is Beautiful'
x = S.rsplit(None,1)
print(x)
# Prints ['The World is', 'Beautiful']
S = 'The World is Beautiful'
x = S.rsplit(None,2)
print(x)
# Prints ['The World', 'is', 'Beautiful']
rsplit() vs split()
If maxsplit is specified, rsplit()
counts splits from the right end, whereas split() counts them from left. Otherwise, they both behave exactly the same.
# rsplit()
S = 'The World is Beautiful'
x = S.rsplit(None,1)
print(x)
# Prints ['The World is', 'Beautiful']
# split()
S = 'The World is Beautiful'
x = S.split(None,1)
print(x)
# Prints ['The', 'World is Beautiful']