Yandex

Python String rsplit() Method – Split from the Right


Python String rsplit() Method

The rsplit() method in Python is used to split a string from the right. It returns a list of substrings, just like split(), but starts splitting from the end of the string.

Syntax

string.rsplit([separator[, maxsplit]])

Parameters:

  • separator (optional): The delimiter on which to split the string. If not provided, any whitespace is considered as the separator.
  • maxsplit (optional): Maximum number of splits. The splitting starts from the right.

Returns:

  • A list of strings after splitting.

Example 1: Basic Usage of rsplit()

text = "apple,banana,cherry"
result = text.rsplit(",")
print(result)
['apple', 'banana', 'cherry']

Example 2: Using maxsplit

text = "apple,banana,cherry"
result = text.rsplit(",", 1)
print(result)
['apple,banana', 'cherry']

Here, only 1 split is done, and it starts from the right.

Example 3: Without Separator (Splits on Whitespace)

text = "Python is beginner friendly"
result = text.rsplit()
print(result)
['Python', 'is', 'beginner', 'friendly']

Key Differences: split() vs rsplit()

  • split() splits from the left (start).
  • rsplit() splits from the right (end).
  • Both accept the same parameters and return a list.

Use Cases

  • When you only want to split the last few items in a string.
  • Parsing file paths, logs, or reversed values.

Common Mistakes

  • Forgetting that maxsplit works from the right.
  • Expecting rsplit() to modify the string (it returns a new list).

Practice Problem

Split the string "2025-05-14" into day, month, and year using rsplit("-", 1). What will be the result?

date = "2025-05-14"
print(date.rsplit("-", 1))

Expected Output:

['2025-05', '14']

Summary

  • rsplit() splits a string into a list, starting from the right.
  • Use maxsplit to control how many splits you want.
  • If no separator is given, whitespace is used.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M