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
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']