The split() function in python helps to return a list of strings by splitting the original string using the specified separator.
str.split([separator [, maxsplit]]) #where separator may be a character,symbol,or space
The split() function takes two parameters. If the separator parameter is not given, it takes any whitespace (space, newline, etc.) as a separator.
Parameter | Description | Required / Optional |
---|---|---|
separator | It is a delimiter. The string splits at the specified separator. | optional |
maxsplit | The maxsplit defines the maximum number of splits. The default value of maxsplit is -1. |
optional |
The return value is a list of strings. If the split count is maxsplit then we have maxsplit+1 items in the output list. In case if the specified separator, not found then a list with the whole string as an element is returned as output.
Input | Return Value |
---|---|
string | list of strings |
string= 'Hii How are you'
# splits at space
print(string.split())
fruits= 'apple, orange, grapes'
# splits at ','
print(fruits.split(', '))
# Splits at ':' but not exist so return original
print(fruits.split(':'))
Output:
['Hii', 'How', 'are', 'you'] ['apple', 'orange', 'grapes'] ['apple, orange, grapes']
fruits= 'apple, orange, grapes, strawberry'
# maxsplit: 2
print(fruits.split(', ', 2))
# maxsplit: 1
print(fruits.split(', ', 1))
# maxsplit: 5
print(fruits.split(', ', 5))
# maxsplit: 0
print(fruits.split(', ', 0))
Output:
['apple', 'orange', 'grapes, strawberry'] ['apple', 'orange, grapes, strawberry'] ['apple', 'orange', 'grapes', 'strawberry'] ['apple, orange, grapes, strawberry']