.split()
Published Jun 9, 2021Updated Jan 9, 2023
Contribute to Docs
The .split()
method returns a new list of substrings based on a given string.
Syntax
string.split(delimiter, number_of_items)
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. - A maximum
number_of_items
for the returned list.
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
number_of_items
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
Looking to contribute?
- 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.