Tutorial Study Image

Python split()

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
 

split() Parameters:

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

split() Return Value

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

Examples of split() method in Python

Example 1: How split() method works in Python?



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

Example 2: Working of split() when maxsplit is specified?


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