Python String rsplit

Python String.rsplit() is used to split this string by given separator string into specified maximum number of items. rsplit() splits the string from right side. rsplit() method returns the parts as a list of strings.

In this tutorial, we will learn the syntax and examples for rsplit() method of String class.

Syntax

The syntax to call rsplit() method on string x in Python is

x.rsplit(sep, maxsplit)

where

Parameter Required / Optional Description
sep Optional A string. Specifies the separator using which this string has to be split into parts. Default value is any whitespace is a separator.
maxsplit Optional A number. Specifies the maximum number of splits that can happen for this string. Default value is -1, meaning no limit on the number of splits.

Examples

In the following program, we take a string 'apple banana cherry', and split this string using rsplit() method, with no values passed for parameters.

Example.py

x = 'apple banana cherry'
result = x.rsplit()
print(result)

Output

['apple', 'banana', 'cherry']

Now, let us specify a separator for rsplit() method. In the following program, we take a string where the items are separated by comma. We shall split this string using separator sep=','.

Example.py

x = 'apple,banana,cherry'
result = x.rsplit(sep=',')
print(result)

Output

['apple', 'banana', 'cherry']

If we specify the maximum number of splits for the rsplit() method, the number of splits is limited to this number.

In the following example, we specify maxsplit=2. Therefore, the maximum number of splits that happen on this string is 2.

Example.py

x = 'hello,world,apple,banana,mango'
result = x.rsplit(sep=',', maxsplit=2)
print(result)

Output

['hello,world,apple', 'banana', 'mango']

Since there are two splits, the original string is split into three parts.

Conclusion

In this Python Tutorial, we learned how to split a string from right side, using rsplit() method, with examples.