Python String split()

The split() method splits a string at the specified separator and returns a list of substrings.

Example

cars = 'BMW-Telsa-Range Rover'

# split at '-' print(cars.split('-'))
# Output: ['BMW', 'Tesla', 'Range Rover']

Syntax of String split()

The syntax of split() is:

str.split(separator, maxsplit)

split() Parameters

The split() method takes a maximum of 2 parameters:

  • separator (optional)- Delimiter at which splits occur. If not provided, the string is splitted at whitespaces.
  • maxsplit (optional) - Maximum number of splits. If not provided, there is no limit on the number of splits.

split() Return Value

The split() method returns a list of strings.


Example 1: How split() works in Python?

text= 'Love thy neighbor'

# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread' # splits at ','
print(grocery.split(', '))
# Splits at ':' print(grocery.split(':'))

Output

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

Here,

  • text.split() - splits string into a list of substrings at each space character
  • grocery.split(', ') - splits string into a list of substrings at each comma and space character
  • grocery.split(':') - since there are no colons in the string, split() does not split the string.

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

The maxsplit parameter is an optional parameter that can be used with the split() method in Python.

It specifies the maximum number of splits to be performed on a string.

Let's see an example,

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))

Output

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

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

Did you find this article helpful?