Menu Close

Python string rsplit() method

python string rsplit

In this article, you will learn about the Python string rsplit() method along with examples.rsplit function in Python is a string built-in function that split the string from the right.

In the previous tutorial, we have seen a Python string rpartition method is used to return the last index of a specified occurrence.

Python string rsplit() method

Python string rsplit() method is used to split the string from right using separator as delimiter and return a list. If any separator is not specified, Then whitespace will be the default separator.
rsplit() string is different from split() method because it split string from the right. If maxsplit parameter is not specified, Then rsplit function works the same as the string split() function.

Syntax

The syntax of rsplit function in Python is:-

string.rsplit(separator, maxsplit)

Parameter

The rsplit function in Python takes two parameters.

  • separator = Optional. Specify the separator to use when splitting the string. By default, it is used whitespace as a separator.
  • maxsplit = Optional. How many split you want to do. By default value is -1 which represent all occurrence.

Return Value

The Python string rsplit method return list which contains all splitted items.

Python string rsplit() examples

Here we will take some examples to understand rsplit function in Python.

Example 1:

a = 'Programming Funda is a educational website'
result = a.rsplit(' ')
print(result)

Output

['Programming', 'Funda', 'is', 'a', 'educational', 'website']

Example 2:

a = 'Programming Funda is a educational website'
result = a.rsplit(' ',-1)
print(result)

Output

['Programming', 'Funda', 'is', 'a', 'educational', 'website']

As you can see in above example, we provided maxsplit -1 that means all occurrence.So you can avoud it.

Example 3:

a = 'Programming Funda is a educational website'
result = a.rsplit(' ',maxsplit=3)
print(result)

Output

['Programming Funda is', 'a', 'educational', 'website']

In above example we have splitted the string from the right with maximum 3 items.

Conclusion

In this tutorial, you have learned the Python string rsplit method to split the string from the right and return a list. You can iterate the return list using python for a loop.

This is the best way to split the string from the right.I hope this tutorial will have helped you. If you like this article, please share it with your friends who want to learn Python programming.

Other string methods


For More Information:- Click Here

Previous Article
Next Article

Related Posts

Leave a Reply