.rsplit()
The .rsplit()
method in Python is a string method that splits a string into a list of substrings from the right end of the string based on a specified delimiter. It is similar to the .split()
method but works in the opposite direction.
Syntax
str.rsplit(separator, maxsplit)
str
: The string to be split.separator (optional)
: This is the delimiter based on which the string will be split. If not specified, any whitespace (spaces, tabs, and newlines) will be used as the separator.maxsplit (optional)
: This parameter specifies the maximum number of splits. It determines the maximum number of elements in the returned list. If not specified or set to-1
, there is no limit on the number of splits.
Example 1
In this example, the .rsplit()
method is applied to the string sentence
without specifying a separator. It splits the string from the right based on whitespace, resulting in a list of words.
sentence = "This is a sample sentence."words = sentence.rsplit()print(words)
This results in the following output:
['This', 'is', 'a', 'sample', 'sentence.']
Example 2
In this example, the .rsplit()
method is employed to split the full_name
string from the right, with a maxsplit
parameter set to 1
. This effectively separates the last name from the rest of the full name.
full_name = "John Doe Smith"first_name, last_name = full_name.rsplit(maxsplit=1)print("First Name:", first_name)print("Last Name:", last_name)
This results in the following output:
First Name: John DoeLast Name: Smith
Codebyte Example
The code below is runnable and uses .rsplit()
to split csv_data
:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Skill path
Analyze Data with Python
Learn to analyze and visualize data using Python and statistics.Includes 8 CoursesWith CertificateIntermediate13 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours