Python String rsplit()
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.
Below we have a basic syntax of the
rsplit() string method in Python:
Note: In the above syntax str is used to denote the main string and on this string
rsplit() method will be applied.
The description of the parameters of this method is as follows:
This is the first parameter based on this, the
rsplit()method splits the string from the right side.
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.
rsplit(): Returned Values
This method returns a list containing the substrings.
rsplit(): Basic Example
Below we have an example to show the working of String
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.
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() 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:
In this tutorial, we learned the
rsplit() method which splits the string from its right side on the basis of the separator.