The split()
method in Python splits a string at the specified operator and converts it into a list of strings.
The syntax of this method is given below:
string.split(separator, maxsplit)
The split()
function has two optional parameters, which are described as:
separator
: specifies the character at which the split should occur. If unspecified, the default is white spaces.
maxsplit
: tells the maximum number of splits that should occur. Its default value is -1, which means the split should occur at all (either specified or whitespace) occurrences.
The return value of this method is a list of strings.
The split()
method returns the list of strings sliced at the specified operators in the code below.
When the operator is unspecified, the string is split at white spaces.
In the last example, maxsplit
is specified as 2 and hence splits the string at two points, returning a list of length 3.
string1 = 'Welcome to Educative'# splits at whitespaceprint(string1.split())string2 = 'Welcome, To, Educative, Courses'# splits at ','print(string2.split(', '))# splits at ',' into three parts i.e a list of len=3print(string2.split(', ', 2))