.split()
Published Jun 9, 2021Updated Oct 6, 2023
Contribute to Docs
The .split()
method returns a new list of substrings based on a given string.
Syntax
string.split(delimiter, maxsplit)
The .split()
method takes the following optional parameters:
- A
delimiter
that is either a regular expression or a string that is composed of one or more characters. - The value
maxsplit
specifies the total number of splits that can occur, and the remainder of the string is returned as the final element of the list. The default value is-1
, which means an unlimited number of splits.
If no parameters are passed to the .split()
method, a list is returned with the string
as the sole element.
Note: An empty string (
""
) cannot be used as adelimiter
to return a list of single characters from a givenstring
. Using the built-inlist()
method can achieve this.
Examples
If the parameters of .split()
are left blank, the delimiter will default to whitespace and the maximum number of items to split will be infinite.
my_string = "I like waffles from Belgium"my_list = my_string.split()print(my_list)# Output: ['I', 'like', 'waffles', 'from', 'Belgium']
The next example shows the following:
- It is possible to use escape characters (tab
\t
, newline\n
, etc.) as delimiters (inlist_a
). - The
maxsplit
can control the size of the returnedlist_b
.
multiline_string = """BeetsBearsBattlestar Galactica"""menu = "Breakfast|Eggs|Tomatoes|Beans|Waffles"list_a = multiline_string.split("\n")list_b = menu.split("|", 3)print(f"Using escape characters: {list_a}")print(f"Limited number of list items: {list_b}")
The following output is shown below:
Using escape characters: ['', 'Beets', 'Bears', 'Battlestar Galactica', '']Limited number of list items: ['Breakfast', 'Eggs', 'Tomatoes', 'Beans|Waffles']
Codebyte Example
The following example showcases a regular expression (r"ea"
) being applied as a delimiter for the .split()
method:
All contributors
- CyberRedPanda
- christ1na
- Anonymous contributor
- BrandonDusch
- christian.dinh
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.