Python String rsplit() Method
Last Updated :
22 Aug, 2022
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
word = 'geeks, for, geeks'
print (word.rsplit( 'g' , 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.
Python3
word = 'geeks, for, geeks, pawan'
print (word.rsplit( ', ' , 0 ))
print (word.rsplit( ', ' , 4 ))
|
Output:
['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', '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"
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 ]
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']
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...