Python string split() method returns a comma-separated list, using separator delimiter. The two parameters of this approach are optional.
The syntax of the method is: str.split(str="", num = string.count(str)).
Key Points :
• This method splits a specified string (the separator is a defined character used between each item) and returns the set of strings.
• The default string separator is whitespace; any separator can also define.
• One of the basic string operations, i.e., splitting of the string, can be performed flexibly with String split().
• Essentially, splitting is toward merger; merging is achieved using concatenation() when splitting a string using split() strings ().
We’ll be covering the following topics in this tutorial:
split() Parameters
The method split() takes up to 2 parameters:
• Separator (optional) – A boundary. The string splits at the separator defined. If the separator is not defined, the separator is a whitespace string (space, newline, etc.)
• maxsplit (optional) – The maximum number of splits determine by maxsplit. The default value for maxsplit is -1, which implies that the number of splits is not capped.
Below is the python program to demonstrate the split() function:
str = "The Best Learning Resource for Online Education"; print (str.split( )) print (str.split(' ', 3 ))
When we run above the program, the outcome is as follows:
[‘The’, ‘Best’, ‘Learning’, ‘Resource’, ‘for’, ‘Online’, ‘Education’]
[‘The’, ‘Best’, ‘Learning’, ‘Resource for Online Education’]
Using “,” as a separator
str = "The Best, Learning Resource, For Online Education" str = str.split(",") print(str)
When we run above the program, the outcome is as follows:
[‘The Best’, ‘ Learning Resource’, ‘ For Online Education’]
Multiline string split() function
str = 'The Best \nLearning Resource \nFor Online Education' str = str.split('\n') for x in str: print(x)
When we run above the program, the outcome is as follows:
The Best
Learning Resource
For Online Education
Multi-Character separator in split() function
str = 'Alpha||Beta||Gamma' str = str.split('||') print(str)
When we run above the program, the outcome is as follows:
[‘Alpha’, ‘Beta’, ‘Gamma’]
Below are several other functions that we can use to work with string in Python 3