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.
string.rsplit(separator, maxsplit)
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.”The rsplit()
method returns a list of strings after splitting the given string from the right side using the given separator.
The following code shows how to use the rsplit()
method in Python.
txt = 'Python is a- programming language'# maxsplit: 0print(txt.rsplit('- ', 0))# maxsplit: 1print(txt.rsplit('- ', 1))txt = 'Python@ is@ a@ programming@ language'# maxsplit: 2print(txt.rsplit('@ ', 2))# maxsplit: 4print(txt.rsplit('@ ', 4))txt = 'Python is a programming language'# separator is 'None',# the txt will be splitted at spaceprint(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.