Open In App

Python String rsplit() Method

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:




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.




# splits the string at index 12
# i.e.: the last occurrence of g
word = 'geeks, for, geeks'
print(word.rsplit('g', 1))
 
# Splitting at '@' with maximum splitting
# as 1
word = 'geeks@for@geeks'
print(word.rsplit('@', 1))

Output: 

['geeks, for, ', 'eeks']
['geeks@for', 'geeks']

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.




word = 'geeks, for, geeks, pawan'
 
# maxsplit: 0
print(word.rsplit(', ', 0))
 
# maxsplit: 4
print(word.rsplit(', ', 4))

Output: 

['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']

Example 3: Practical Example using Python String rsplit() Method




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']

Article Tags :