Python String rsplit()

The Python String rsplit() method is a built-in function that splits the string at the specified separator from the right side and returns a list of strings.

Syntax

The Syntax of rsplit() method is:

str.rsplit(separator, maxsplit)

Parameters

The rsplit() method takes two parameters, and both are optional.

  • separator (optional) – Delimiter after which the string split should happen. If not provided, whitespace is taken as a separator, and the string will split at whitespaces. 
  • maxsplit (optional) – An integer that tells us the maximum number of times the split should happen. If not provided, the default value is -1, which means there is no limit on the number of splits.

Return Value

The rsplit() method returns the list of strings after breaking the given string at the separator from the right side

Example 1: How split() method works in Python

If we do not specify maxsplit argument to rsplit() method, it behaves exactly like split() method as shown in the below example.

# splits by whitespace
text = "Python is fun"
print(text.rsplit())

# splits the text after 'is' string
text = "Python is fun"
print(text.rsplit('is'))

# cannot split as the character is not found
text = "Python is fun"
print(text.rsplit('|'))

# splits by comma
fruits ="Apple, Grapes, Orange, Watermelon"
print(fruits.rsplit(','))

Output

['Python', 'is', 'fun']
['Python ', ' fun']
['Python is fun']
['Apple', ' Grapes', ' Orange', ' Watermelon']

Example 2: Python split() method with maxsplit and separator arguments

# splits by whitespace
text = "Python is really fun"
print(text.rsplit(' ', 1))

# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.rsplit(',', 0))

# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.rsplit(',', 1))

# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.rsplit(',', 2))


# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.rsplit(',', 3))

Output

['Python is really', 'fun']
['Apple, Grapes, Orange, Watermelon']
['Apple, Grapes, Orange', ' Watermelon']
['Apple, Grapes', ' Orange', ' Watermelon']
['Apple', ' Grapes', ' Orange', ' Watermelon']
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Jsonpath

Python JSONPath

Table of Contents Hide JSONPath Library in PythonInstalling jsonpath-ng ModuleJsonpath operators:Parsing a Simple JSON Data using JSONPathParsing a Json Array using JSONPath Expression JSONPath is an expression language that is…
View Post