Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator.
Python String rsplit() Method Syntax:
Syntax: str.rsplit(separator, maxsplit)
Parameters:
- separator: The is a delimiter. The string splits at this specified separator starting from the right side. If not provided then any white space character is a separator.
- maxsplit: It is a number, which tells us to split the string into a maximum of provided number of times. If it is not provided then there is no limit.
Return: Returns a list of strings after breaking the given string from the right side by the specified separator.
Error: We will not get any error even if we are not passing any argument.
Python String rsplit() Method Example:
Python3
string = "tic-tac-toe" print (string.rsplit( '-' )) |
Output:
['tic', 'tac', 'toe']
Note: Splitting a string using Python String rsplit() but without using maxsplit is same as using String split() Method
Example 1: Splitting String Using Python String rsplit() Method
Splitting Python String using different separator characters.
Python3
# splits the string at index 12 # i.e.: the last occurrence of g word = 'Lazyroar, for, Lazyroar' print (word.rsplit( 'g' , 1 )) # Splitting at '@' with maximum splitting # as 1 word = 'Lazyroar@for@Lazyroar' print (word.rsplit( '@' , 1 )) |
Output:
['Lazyroar, for, ', 'eeks'] ['Lazyroar@for', 'Lazyroar']
Example 2: Splitting a String using a multi-character separator argument.
Here we have used more than 1 character in the separator string. Python String rsplit() Method will try to split at the index if the substring matches from the separator.
Python3
word = 'Lazyroar, for, Lazyroar, pawan' # maxsplit: 0 print (word.rsplit( ', ' , 0 )) # maxsplit: 4 print (word.rsplit( ', ' , 4 )) |
Output:
['Lazyroar, for, Lazyroar, pawan'] ['Lazyroar', 'for', 'Lazyroar', 'pawan']
Example 3: Practical Example using Python String rsplit() Method
Python3
inp_todo_string = "go for walk:buy pen:buy grocery:prepare:take test:sleep" # define function to extract last n todos def get_last_todos(todo_string, n): todo_list = todo_string.rsplit( ':' , n) print (f "Last {n} todos: {todo_list[-n:]}" ) return todo_list[ 0 ] # call function to get last n todo's inp_todo_string = get_last_todos(inp_todo_string, 1 ) inp_todo_string = get_last_todos(inp_todo_string, 2 ) inp_todo_string = get_last_todos(inp_todo_string, 1 ) |
Output:
Last 1 todos: ['sleep'] Last 2 todos: ['prepare', 'take test'] Last 1 todos: ['buy grocery']