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 |
maxsplit | The |
Return Values
rsplit()
returns a list of strings resulting from the split operation.
How to Use rsplit()
in Python
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)
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)
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)