Signup/Sign In
LAST UPDATED: JUNE 9, 2020

Python String rsplit()

The Python rsplit() string method is used to split the string on the basis of the given separator from the right side of the string.

  • This method returns a list of substrings after dividing the string based on the separator.

  • The separator can be any character, any alphabet, a number or if you do not provide any separator character then blank space is taken as the default separator.

Python String rsplit(): Syntax

Below we have a basic syntax of the rsplit() string method in Python:

str.rsplit(separator, max)

Note: In the above syntax str is used to denote the main string and on this string rsplit() method will be applied.

Python String rsplit(): Parameters

The description of the parameters of this method is as follows:

  • separator

    This is the first parameter based on this, the rsplit() method splits the string from the right side.

  • max

    It is used to define how many times we want to split the string, when the separator is found. If this is not mentioned then the string is split until the separator is found in the string.

Python String rsplit(): Returned Values

This method returns a list containing the substrings.

Python String rsplit(): Basic Example

Below we have an example to show the working of String rsplit() method:

str = "hello once again my friends!!"
print("String before split: ", str)
print("String after split: ", str.rsplit(" ", 2))

The Output For the same will be:


String before split: hello once again my friends!!
String after split: ['hello once again', 'my', 'friends!!']

In the code example above, we have provided the max parameter value 2, to split the string 2 times only, hence we got 3 substrings in the list. If we remove the max parameter, the string will be split at each blank space.

Python split() vs rsplit()

Both Python split() string method and rsplit() function are the same, but the only difference is that rsplit() is used to split the string from the right side which is not the case with split(). The split() function splits the string from the first occurrence starting from the left side.

Time for Live Example!

Let us see a live example below where we use rsplit() function in different ways:

Summary

In this tutorial, we learned the rsplit() method which splits the string from its right side on the basis of the separator.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.