In this tutorial, we’ll learn what Python string rsplit() method is and how to properly use it. We’ll go through multiple Python code examples to understand how rsplit method works.
Introduction: Python String rsplit() Method
This method splits a string starting from the right/end and return a list of strings. We can specify from which character/substring, the string should break. If not specified any, then whitespaces will be used.
Syntax of rsplit() Method
string.rsplit(separator(optional), maxSplitNumbers(optional))
- Python string rsplit method takes two arguments.
- First argument is used to specify which character should be used to split/break the string.
- Second argument specify the number of splits that should be performed.
- This method starts splitting the string from right/end.
- Python string rsplit method return a list of substrings after breaking/splitting the main string.
Example 1: rsplit() Method applied on a Python String
print('a,b,c,d,e,f'.rsplit(',')) print('Python Programming language'.rsplit()) print('Python Programming'.rsplit('program')) // Program(capital P) is present by program is not print('Python_Programming_Language'.rsplit('_')) print('Python $Programming $Python $language'.rsplit('$'))
Output
['a', 'b', 'c', 'd', 'e', 'f'] ['Python', 'Programming', 'language'] ['Python Programming'] ['Python', 'Programming', 'Language'] ['Python ', 'Programming ', 'Python ', 'language']
This is how Python string rsplit method works. You can try it with even more examples to better understand the working of this method.
Example 2: rsplit() Method with MaxSplit
print('a b c d e f g h'.rsplit(' ',4)) // whitespace separator used print('a,b,c,d,e,f,g,h'.rsplit(',',1)) print('a,b,c,d,e,f,g,h'.rsplit(',',3)) print('a-b-c-d-e-f-g-h'.rsplit('-',0)) print('a,b,c,d,e,f,g,h'.rsplit('',2)) // empty separator gives error
Output
['a', 'b', 'c', 'd,e,f,g,h'] ['a-b-c-d-e-f-g-h'] ['a', 'b', 'c', 'd', 'e f g h'] ['a', 'b,c,d,e,f,g,h'] ValueError: empty separator
So this is how we can limit the number of splits in a string. Splitting starts from right and can be seen in the above given examples.
Example 3: Python String rsplit() Method Return Value
val= 'a, d,e,f,g,bb,c,h' returnedVal=val.rsplit(',',4) print(returnedVal)
Output
['a, d,e,f', 'g', 'bb', 'c', 'h'] // splitting starts from the right/end
Python string rsplit method has returned a list of substrings after splitting the main string. This method uses whitespace as a default separator, if no other separator is specified.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string rsplit method. I’d be very happy to receive your feedback on this post. Thank you for reading it.