Table of Contents
The rsplit() method splits string from the right at the specified separator and returns a list of strings.
The syntax of rsplit() is:
str.rsplit([separator [, maxsplit]])
1. rsplit() Parameters
rsplit() method takes maximum of 2 parameters:
- separator (optional)- The is a delimiter.
rsplit()method splits string starting from the right at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a separator. - maxsplit (optional) – The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.
2. Return Value from rsplit()
rsplit() breaks the string at the separator starting from the right and returns a list of strings.
3. Example 1: How rsplit() works in Python?
text= 'Love thy neighbor'
# splits at space
print(text.rsplit())
grocery = 'Milk, Chicken, Bread'
# splits at ','
print(grocery.rsplit(', '))
# Splitting at ':'
print(grocery.rsplit(':'))
Output
['Love', 'thy', 'neighbor'] ['Milk', 'Chicken', 'Bread'] ['Milk, Chicken, Bread']
When maxsplit is not specified, rsplit() behaves like split().
4. Example 2: How split() works when maxsplit is specified?
grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.rsplit(', ', 2))
# maxsplit: 1
print(grocery.rsplit(', ', 1))
# maxsplit: 5
print(grocery.rsplit(', ', 5))
# maxsplit: 0
print(grocery.rsplit(', ', 0))
Output
['Milk, Chicken', 'Bread', 'Butter'] ['Milk, Chicken, Bread', 'Butter'] ['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk, Chicken, Bread, Butter']
If maxsplit is specified, the list will have the maximum of maxsplit+1 items.
Related posts:
Python Program to Merge Two Dictionaries
Python Program to Copy a File
Python Program to Return Multiple Values From a Function
Python Set symmetric_difference_update()
JavaScript Methods of RegExp and String
Python Program Read a File Line by Line Into a List
Python Custom Exceptions
Python List
Python oct()
Python Program to Trim Whitespace From a String
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Make a Simple Calculator
Python Program to Catch Multiple Exceptions in One Line
Python Program to Display the multiplication Table
Python Program to Remove Punctuations From a String
Converting String to Stream of chars
Python slice()
Python Program to Find Armstrong Number in an Interval
Python id()
Python min()
Python String zfill()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Check If a List is Empty
Python Set clear()
Python Program to Append to a File
Python any()
Java – Generate Random String
Check If a String Is Numeric in Java
Python Operators
Convert char to String in Java
Python Global, Local and Nonlocal variables
String Processing with Apache Commons Lang 3