Python String rsplit method with Example – Python Tutorial
3 months ago Lalit Bhagtani 0
In this tutorial, we will learn about python string rsplit method.
rsplit method :
This method divide ( split ) the string in to multiple parts, using separator ( sep ) passed as an argument and return all of these parts as a list. rsplit method is very similar to split method with the difference is that rsplit method divide the string from right side while split method divide the string from left side.
Syntax : < String Object >.rsplit( sep , maxsplit ) : < List Object >
sep : It is a separator string used by method to divide the given string.
maxsplit : It is the maximum number of divide that the method can perform.
# Case 1 : sep = '@' sep_1 = '@' s_1 = 'abc@def@ghi@jkl' l_1 = s_1.rsplit(sep_1) print('case 1: ') print(l_1) # Case 2 : sep = ' ' maxSplit = 2 sep_2 = ' ' maxSplit_2 = 2 s_2 = 'abc def ghi jkl' l_2 = s_2.rsplit(sep_2,maxSplit_2) print('case 2: ') print(l_2) # In this case, rsplit method will divide the string (s2) 2 times as maxSplit is 2, So list will have 3 elements. # Case 3 : sep = '@' maxSplit = 5 sep_3 = '@' maxSplit_3 = 5 s_3 = 'abc@def@ghi@jkl@mno' l_3 = s_3.rsplit(sep_3,maxSplit_3) print('case 3: ') print(l_3) # In this case, rsplit method will divide the string (s3) 4 times, as separator string ('@') is present only 4 times, So list will have 3 elements. # Case 4 : sep = None or sep not passed sep_4 = None s_4 = 'abc def ghi jkl' l_4 = s_4.rsplit(sep_4) # l_4 = s_4.rsplit() can also be used. print('case 4: ') print(l_4) # In this case, rsplit method will divide the string s4 by using space as a separator.
That’s all for Python String rsplit method. If you liked it, please share your thoughts in comments section and share it with others too.