Python String rsplit() Method

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)

Python string rsplit() method parameters
ParameterConditionDescription
delimiterOptionalAny character to split the sting with.
Default is whitespace.
maxsplitOptionalA 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.

Example: Split a string on whitespace

S = 'The World is Beautiful'
x = S.rsplit()
print(x)    # ['The', 'World', 'is', 'Beautiful']

Split on a Delimiter

You can split a string by specifying a delimiter.

Example: Split on comma

S = 'red,green,blue'
x = S.rsplit(',')
print(x)	# ['red', 'green', 'blue']

Example: Delimiter with multiple characters

S = 'the beginning is the end is the beginning'
x = S.rsplit(' is ')
print(x)	# ['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 list will have the specified number of elements plus one.

Example: Limit splits in rsplit() method

S = 'The World is Beautiful'
x = S.rsplit(None,1)
print(x)	# ['The World is', 'Beautiful']
S = 'The World is Beautiful'
x = S.rsplit(None,2)
print(x)	# ['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.

Example:

# rsplit()
S = 'The World is Beautiful'
x = S.rsplit(None,1)
print(x)	# ['The World is', 'Beautiful']
# split()
S = 'The World is Beautiful'
x = S.split(None,1)
print(x)	# ['The', 'World is Beautiful']