Python String rsplit() Method Tutorial

In this section, we will learn what String rsplit() method is and how to use it in Python.

What is String rsplit() Method in Python?

The Python string rsplit() method is used to split a string value into sub-strings (starting from the right side of the right side of that string) and return those sub-strings in a list as a result.

Note: if you don’t specify the second argument of the method (the number of times to split the string) then this method acts the same as the split() method.

Python String rsplit() Method Syntax:

string.rsplit(separator, maxsplit)

String rsplit() Method Parameter

The method takes two arguments:

  • The first argument is the separator that will be used to split the target string. By default, this value is set to a white space. That means anywhere in the string that there’s a white space of any kind (newline or tab etc.) that will be the point where the string splits. But we can change this value to other characters.
  • The second argument is the number of times that the string should split. The default value is set to -1 and that means split the string as long as there’s a separator in the string that could be used for this purpose. But if you change this value to something like 2, that means only split the target string 2 times starting from the right side.

String rsplit() Method Return Value

The return value of this method is a reference to a list object that contains the sub-values of the target string as a result of invoking this method on it.

Example: using python string rsplit() method

s1 = "My name is John Doe and my cousin's name is also the same as mine! "

print(s1.rsplit("name",1))

Output:

["My name is John Doe and my cousin's ", ' is also the same as mine! ']
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies