The Python string rsplit() method is used to split a string into a list of substrings, starting from the right end of the string. It is similar to the split() method, but instead of splitting from the left (beginning), it starts splitting from the right.
This method can be useful when dealing with structured data or when parsing strings where the relevant information is located towards the end.
SyntaxFollowing is the basic syntax of the Python String rsplit() method −
string.rsplit(sep = None, maxsplit = -1)Parameter
This method accept the following parameters −
sep (optional) − It is the separator used to split the string. If "sep" is not specified or is None, the method splits the string using whitespace characters (space, tab, newline, etc.).
maxsplit (optional) − It is the maximum number of splits to perform. If maxsplit is -1 (the default), all occurrences of the separator are considered for splitting.
The method returns a list of substrings obtained by splitting the original string.
ExampleIn the following example, we are splitting the string "text" using the comma "," as the delimiter from the right end −
text = "apple,banana,orange" result = text.rsplit(',') print(result)Output
The output obtained is as follows −
['apple', 'banana', 'orange']Example
Here, we limit the split operation to only one split, resulting in a list with two elements. The last comma is used as the split point, and the remaining part of the string is kept as a single element in the list −
text = "apple,banana,orange" result = text.rsplit(',', 1) print(result)Output
Following is the output of the above code −
['apple,banana', 'orange']Example
If we does not provide any delimiter, the rsplit() method splits the string based on whitespace characters by default.
If there are no whitespace characters in the string, the method returns a list containing the original string as the only element −
text = "apple,banana,orange" result = text.rsplit() print(result)Output
The result produced is as shown below −
['apple,banana,orange']Example
Now, we are splitting the string text based on whitespace characters. Multiple consecutive whitespaces are treated as a single delimiter, resulting in a list of substrings without any empty elements −
text = "apple banana orange" result = text.rsplit() print(result)Output
We get the output as shown below −
['apple', 'banana', 'orange']
split_and_join.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4