Python String split() method
The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is not specified, then there is no limit on the number of splits.
Syntax
split([sep [,maxsplit]])
Parameter
sep(optional) : This parameter Specifies the separator to use when splitting the string. The default value is whitespace. If the parameter ‘sep’ is not specified or is none, a different splitting algorithm is applied.
Maxsplit(optional) : This parameter specifies how many splits to do. The Default value is -1, which is "all occurrences".
Return
This method returns a list of the words in the string, using sep as the delimiter string.
Example 1
# Python program explaining # the string.split() method # initializing the string string = "Python Java C# Ruby" print("Original string...") print(string) # spliting the string when whitespaces ocures print("After spliting the string …") print(string.split())
Output
Original string... Python Java C# Ruby After spliting the string … ['Python', 'Java', 'C#', 'Ruby']
Example 2
# Python program explaining # the string.split() method string = "Tutorials and Examples" # By default this method Splits at space print(string.split()) # Splits at 'g'. As the maximum limit as 1. # So splitting occurs at second t string = "Tutorials, and, Examples" print(string.split('t', 1)) # Splitting at '$' with maximum splitting # as 1 string = "Tutorials$and$Examples" print(string.split('$', 1))
Output
['Tutorials', 'and', 'Examples'] ['Tu', 'orials, and, Examples'] ['Tutorials', 'and$Examples']
Example 3
# Python program explaining # the string.split() method # initializing the string string = "Tutorials, and, Examples" # maxsplit: 0 print(string.split(', ', 0)) # maxsplit: 4 print(string.split(', ', 4)) # maxsplit: 1 print(string.split(', ', 1))
Output
['Tutorials, and, Examples'] ['Tutorials', 'and', 'Examples'] ['Tutorials', 'and, Examples']