The Python rsplit function divides a string and produces a list as output. This method performs the split operation starting from the end of the string, utilizing the specified separator as a delimiter. In cases where no separator is provided, it defaults to using any whitespace character as the delimiter. Essentially, this function operates similarly to split, with the key distinction being that it initiates the split from the right side, which is elaborated upon in the following sections.
Note: if separator is not given, whitespace is treated as separator.
Syntax of Python String rsplit Method
It has the following syntax:
rsplit(sep=None,maxsplit=-1)
Parameters
- sep: A string parameter acts as a seperator.
- maxsplit: number of times split perfomed.
Return
It returns a comma separated list.
Different Examples for Python String rsplit Method
Let's explore a few instances of the rsplit method to gain a clearer insight into its capabilities.
Example 1
This serves as a straightforward illustration to grasp the application of the rsplit function.
# Python rsplit() method example
# Variable declaration
str = "Python is a programming language"
# Calling function
str2 = str.rsplit()
# Displaying result
print(str2)
Output:
['Python', 'is', 'a', 'programming', 'language']
Example 2
Let’s provide a parameter separator to the function; refer to the following example.
# Python rsplit() method example
# Variable declaration
str = "Python is a programming language"
# Calling function
str2 = str.rsplit('Python')
# Displaying result
print(str2)
Output:
['', ' is a programming language']
Example 3
The string is divided every time the character 'a' appears. Refer to the example provided below.
# Python rsplit() method example
# Variable declaration
str = "Python is a programming language"
# Calling function
str2 = str.rsplit('a')
# Displaying result
print(str2)
Output:
['J', 'v', ' is ', ' progr', 'mming l', 'ngu', 'ge']
Example 4
In addition to the separator, we also have the option to provide a maxsplit value. The maxsplit parameter determines how many times the string will be divided.
# Python rsplit() method example
# Variable declaration
str = "Python is a programming language"
# Calling function
str2 = str.rsplit('a',1)
# Displaying result
print(str2)
str2 = str.rsplit('a',3)
# Displaying result
print(str2)
Output:
['Python is a programming langu', 'ge']
['Python is a progr', 'mming l', 'ngu', 'ge']