English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python String split() Usage and Example

Python string methods

The split() method splits 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 can use at most2a parameter:

  • separator(Optional)-is the separator. The string is split at the specified separator (separator). 
    If the separator is not specified, any space (space, newline, etc.) string is a separator.

  • maxsplit(Optional)- maxsplit defines the maximum number of splits.
    The default value is maxsplit-1means that the split number is unlimited.

split() return value

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

Example1:How does split() work in Python?

text = 'Love thy neighbor'
# Split at space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# Split at ','
print(grocery.split(', '))
# Split at ':'
print(grocery.split(':'))

When running the program, the output is:

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

Example2:How does split() work 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 running the program, the output is:

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

If maxsplit is specified, the list will contain at most maxsplit+1project.

Python string methods