Python String | rsplit method
Start your free 7-days trial now!
Python's str.rsplit(~) method splits up the string based on the specified separator, and returns a list containing the separated items. As opposed to str.split(~) which splits from the left, str.rsplit(~) splits from the right.
Parameters
1. sep | string | optional
The separator used to split up the string. By default, sep=" " (i.e. a single space).
2. maxsplit | number | optional
The maximum number of splits you want to make. By default, maxsplit=-1 (i.e. no maximum set).
Return value
A list of separated strings.
Examples
Sep parameter
By default, the separator used is a single white space:
x = "a b c"x.rsplit()
['a', 'b', 'c']
To split by comma instead:
y = "a,b,c"y.rsplit(",")
['a', 'b', 'c']
Sep does not exist in string
To split "abc" using comma as the separator:
z = "abc"z.rsplit(",")
['abc']
We return a list with the original string as the sole element as the separator did not exist in the string.
Maxsplit parameter
To split "a,b,c" at most once:
w = "a,b,c"w.rsplit(",", 1))
['a,b', 'c']
The splitting happens only once from the right despite the fact that we have two commas.