Python String split() method (With Examples)

split() method is used to break up a bigger string into a smaller list of strings. We need to specify a separator(default separator is a whitespace if not specified) to help in splitting of the string. As a result we get a list where each word is a separate list item. In other words split() is used to split a string into a list.

Syntax

str.split(separator, maxsplit)

Parameters


separator
This is any delimiter which is used to split the string. If it is not provided any whitespace(space, newline etc.) is considered as default.
maxsplit

It is a numeric optional value which specifies how many splits will be performed. If maxsplit is not provided then there is no limit. If maxsplit is not specified or -1(all occurrences), then there is no limit on the number of splits (all possible splits will be made).
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Returns

Returns a list of strings which has been split by the specified separator. The split() splits the string at the separator and returns a list of strings.

Below examples shows Python split string by comma, python split string by character and python split string by space.

Example 1

textstring = 'Coding is Fantastic'
# Split() at space 
print(textstring.split()) 
wordstring = 'Coding, is, Fantastic'
# Split() at ',' 
print(wordstring.split(', ')) 
wordstring = 'Coding#is#Fantastic'
# Splitting at '#' 
print(wordstring.split('#')) 
Output


['Coding', 'is', 'Fantastic']
['Coding', 'is', 'Fantastic']
['Coding', 'is', 'Fantastic']

Example 2 


wordstring = 'Apple, Orange, Grapes, Kiwi'
# maxsplit: 0 
print(wordstring.split(', ', 0)) 
# maxsplit: 3 
print(wordstring.split(', ', 3)) 
# maxsplit: 1 
print(wordstring.split(', ', 1)) 
Output

['Apple, Orange, Grapes, Kiwi']
['Apple', 'Orange', 'Grapes', 'Kiwi']
['Apple', 'Orange, Grapes, Kiwi']

Further Read: