Python String split method with Example – Python Tutorial
1 week ago codedestine 0
In this tutorial, we will learn about python string split method.
Python String split 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.
Syntax : < String Object >.split( 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.split(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.split(sep_2,maxSplit_2) print('case 2: ') print(l_2) # In this case, split 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.split(sep_3,maxSplit_3) print('case 3: ') print(l_3) # In this case, split 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.split(sep_4) # l_4 = s_4.split() can also be used. print('case 4: ') print(l_4) # In this case, split method will divide the string s4 by using space as a separator.
That’s all for Python String split method. If you liked it, please share your thoughts in comments section and share it with others too.