Python String split()

The split() method breaks up a string at the specified separator and returns a list of strings.

The syntax of split() is:

str.split([separator [, maxsplit]])

split() Parameters

The split() method takes maximum of 2 parameters:

  • separator (optional)- The is a delimiter. The string splits at the specified separator.
    If the separator is not specified, any whitespace (space, newline etc.) string is a separator.
  • maxsplit (optional) - The maxsplit defines the maximum number of splits.
    The default value of maxsplit is -1, meaning, no limit on the number of splits.

Return Value from split()

The split() breaks the string at the separator and returns a list of strings.

Example 1: How split() works in Python?

text= 'Love thy neighbor'

# splits at space

grocery = 'Milk, Chicken, Bread'

# splits at ','
print(grocery.split(', '))

# Splitting at ':'

When you run the program, the output will be:

['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']

Example 2: How split() works when maxsplit is specified?

grocery = 'Milk, Chicken, Bread, Butter'

# maxsplit: 2
print(grocery.split(', ', 2))

# maxsplit: 1
print(grocery.split(', ', 1))

# maxsplit: 5
print(grocery.split(', ', 5))

# maxsplit: 0
print(grocery.split(', ', 0))

When you run the program, the output will be:

['Milk', 'Chicken', 'Bread, Butter']
['Milk', 'Chicken, Bread, Butter']
['Milk', 'Chicken', 'Bread', 'Butter']
['Milk, Chicken, Bread, Butter']

If maxsplit is specified, the list will have the maximum of maxsplit+1 items.