What is the String rsplit() method in Python?

Python comes with a lot of built-in methods, such as the rsplit() method.

The rsplit() method is used to return a list of strings after splitting the given string from the right side with the given separator.

Syntax

string.rsplit(separator, maxsplit)

Parameters

  • separator: An optional delimiter. When splitting the string, the separator parameter specifies the separator to use. If the parameter is not specified, any white space will be used as a separator.
  • maxsplit: This optional parameter specifies the number of splits to do. The default value is -1, which is “all occurrences.”

Return value

The rsplit() method returns a list of strings after splitting the given string from the right side using the given separator.

Code

The following code shows how to use the rsplit() method in Python.

txt = 'Python is a- programming language'
# maxsplit: 0
print(txt.rsplit('- ', 0))
# maxsplit: 1
print(txt.rsplit('- ', 1))
txt = 'Python@ is@ a@ programming@ language'
# maxsplit: 2
print(txt.rsplit('@ ', 2))
# maxsplit: 4
print(txt.rsplit('@ ', 4))
txt = 'Python is a programming language'
# separator is 'None',
# the txt will be splitted at space
print(txt.rsplit(None, 1))
print(txt.rsplit(None, 2))

In the above code, we create a variable named txt that holds the word. Next, we use the rsplit() method with the parameters separator and maxsplit.

Note: If no separator is provided, the white space is used for the splitting.

Free Resources