Skip to main content

rsplit()

The rsplit() method in Python is a string method that splits a string into a list of substrings based on the specified delimiter. It works similar to the split() method, but it starts the splitting from the right end of the string instead. If no delimiter is provided, it splits the string based on whitespace.

Parameter Values

Parameter Description
sep

The sep parameter is a string specifying the separator to use for splitting the string. If not provided, the string will be split using any whitespace characters.

maxsplit

The maxsplit parameter is an integer specifying the maximum number of splits to do. If not provided, there is no limit on the number of splits.

Return Values

rsplit() returns a list of strings resulting from the split operation.

How to Use rsplit() in Python

Example 1:

The rsplit() method splits a string into a list of substrings, starting from the right side. You can specify the maximum number of splits as an argument.

sentence = 'I love Python programming language'
words = sentence.rsplit(' ', 2)
print(words)
Example 2:

If the rsplit() method does not find the specified separator, it will return a list with the original string as the only element.

text = 'Hello'
result = text.rsplit(',')
print(result)
Example 3:

The rsplit() method can be useful when you need to split a string into parts, starting from the right side, like splitting a filename and its extension.

filename = 'document.txt'
parts = filename.rsplit('.', 1)
print(parts)