English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python String rsplit() Usage and Examples

Python String Methods

The rsplit() method splits the string at the specified separator from the right and returns a list of strings.

The syntax of rsplit() is:

str.rsplit([separator[, maxsplit]])

rsplit() parameters

The rsplit() method can accept at most2One parameter:

  • separator(Optional)-This is a separator. The method's purpose is: to split the string from the right at the specified separator.

  • If separator is not specified, any whitespace (spaces, newline characters, etc.) string is considered as a separator.

  • maxsplit(Optional)- maxsplit defines the maximum number of splits.
    The default value is maxsplit-1means the split count is unlimited.

rsplit() return value

The rsplit() method splits the string into a list starting from the right.
If "maxsplit" is not specified, this method will return the same result as the split() method.
Note: If maxsplit is specified, the list will contain one more element than the specified number.

Example1How does rsplit() work in Python?

text = 'Love thy neighbor'
# Split at space
print(text.rsplit())
grocery = 'Milk, Chicken, Bread'
# Split at ','
print(grocery.rsplit(', '))
# Split at ':'
print(grocery.rsplit(':'))

When running the program, the output is:

['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']

If maxsplit is not specified, the behavior of rsplit() is similar to split().

Example2How does split() work when maxsplit is specified?

grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.rsplit(', ')) 2))
# maxsplit: 1
print(grocery.rsplit(', ')) 1))
# maxsplit: 5
print(grocery.rsplit(', ')) 5))
# maxsplit: 0
print(grocery.rsplit(', ', 0))

When running the program, the output is:

['Milk, Chicken', 'Bread', 'Butter']
['Milk, Chicken, Bread', 'Butter']
['Milk', 'Chicken', 'Bread', 'Butter']
['Milk, Chicken, Bread, Butter']

If maxsplit is specified, the list will contain at most maxsplit+1Project.

Python String Methods