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.
Also read How to fix Pandas TypeError: no numeric data to plot
In this article, we will learn about the Python String rsplit()
method with the help of examples.
rsplit() Syntax
The Syntax of rsplit()
method is:
str.rsplit(separator, maxsplit)
rsplit() 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.
rsplit() Return Value
The rsplit()
method returns the list of strings after breaking the given string at the separator from the right side
Also read How to fix Python ValueError: Trailing data
Example 1: How rsplit() works in Python?
If we do not specify maxsplit to rsplit() method it behaves exactly like split() method as shown in 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: How split() works when maxsplit is specified?
# 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']
Top comments (0)