String rsplit() Method in Python

Python String rsplit() Method

In Python, the rsplit() method is used to split a string into a list of substrings from the right side (end) of the string. It is similar to the split() method, but it starts splitting the string from the end and works towards the beginning. This method is particularly useful when you want to extract substrings from the end of a string or when the delimiter appears multiple times in the string, and you only want to split at the rightmost occurrence.

The rsplit() method takes three arguments, but only the first two are commonly used:

str.rsplit(separator, maxsplit)

Parameters:

  • separator (optional): The delimiter character or string used to split the string. If not specified, the default delimiter is any whitespace character (e.g., space, tab, newline).
  • maxsplit (optional): This parameter specifies the maximum number of splits to perform. If not provided, there is no limit on the number of splits, and the entire string will be split.

Here are some examples to illustrate how the rsplit() method works:

Using the default delimiter (whitespace)

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

Using a specific delimiter

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

Using maxsplit to limit the number of splits

text = "apple,banana,cherry,date"
result = text.rsplit(',', maxsplit=1)
print(result)  # Output: ['apple,banana,cherry', 'date']

In this last example, the rsplit() method performs only one split and returns a list with two elements: the substring before the rightmost comma and the substring after it.

Remember that rsplit() returns a list of substrings after splitting the original string. If you want to split a string from the left side (start) instead, you can use the regular split() method.