Skip to content
Related Articles

Related Articles

Python String rsplit() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Aug, 2022
View Discussion
Improve Article
Save Article

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)


  • 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"


['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))


['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))


['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)


Last 1 todos: ['sleep']
Last 2 todos: ['prepare', 'take test']
Last 1 todos: ['buy grocery']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!