The rsplit() function in python helps to return a list of strings by splitting the original string. Here the splitting is starting from the right end and by using the specified separator.
str.rsplit([separator [, maxsplit]]) #where separator may be a character,symbol,or space
The rsplit() function takes two parameters. If the separator parameter is not given, it takes any whitespace (space, newline, etc.) as a separator.
Parameter | Description | Required / Optional |
---|---|---|
separator | It is a delimiter. The string splits at the specified separator. | optional |
maxsplit | The maxsplit defines the maximum number of splits. The default value of maxsplit is -1. |
optional |
The return value is a list of strings. If the split count is maxsplit then we have maxsplit+1 items in the output list. In case if the specified separator, not found then a list with the whole string as an element is returned as output.
Input | Return Value |
---|---|
string | list of strings |
string= 'Hii How are you'
# splits at space
print(string.rsplit())
fruits= 'apple, orange, grapes'
# splits at ','
print(fruits.rsplit(', '))
# Splits at ':' but not exist so return original
print(fruits.rsplit(':'))
Output:
['Hii', 'How', 'are', 'you'] ['apple', 'orange', 'grapes'] ['apple, orange, grapes']
fruits= 'apple, orange, grapes, strawberry'
# maxsplit: 2
print(fruits.split(', ', 2))
# maxsplit: 1
print(fruits.split(', ', 1))
# maxsplit: 5
print(fruits.split(', ', 5))
# maxsplit: 0
print(fruits.split(', ', 0))
Output:
['apple, orange', 'grapes', 'strawberry'] ['apple, orange, grapes', 'strawberry'] ['apple', 'orange', 'grapes', 'strawberry'] ['apple, orange, grapes, strawberry']