Python Reference ยท String Methods
Python str.split() method
Reference for Python str.split(): break a string into a list by a separator or by whitespace, how maxsplit works, empty strings and common mistakes.
The str.split() method breaks a string into a list of substrings. You choose the separator, or leave it out to split on whitespace. It is the standard first step when parsing lines of text, CSV-like data and command arguments.
Calling split() with no arguments behaves differently from split(" "): whitespace mode treats any run of whitespace as one separator and ignores leading and trailing whitespace, so it never yields empty strings.
print("a b c".split()) # ['a', 'b', 'c'] print("a,b,,c".split(",")) # ['a', 'b', '', 'c']
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.split() str.split(sep=None, maxsplit=-1)
| Name | Description |
|---|---|
sep |
Optional. The separator string (any length). If None or omitted, runs of whitespace are separators and empty strings are removed from the result. |
maxsplit |
Optional. The maximum number of splits, counted from the left. -1 (the default) means no limit. |
Return value: a list of strings. With maxsplit, at most maxsplit + 1 items.
Raises: ValueError ("empty separator") if sep is ""; TypeError for wrong types.
Usage notes
split()is notsplit(" "). With an explicit separator, adjacent separators produce empty strings and leading or trailing separators produce empty items at the ends.- No match returns a one-item list with the original string.
"".split(",")is[''], but"".split()is[]. - Multi-character separators work as a whole:
"a--b".split("--"). - To get characters, use
list(s), notsplit(""), which raises. - Unpacking (
a, b = s.split(",")) raisesValueErrorif the count differs. Usemaxsplit,partition()or a check when the input is not trusted. - Several different separators need
re.split();split()only takes one literal separator. - Lines: use
splitlines(), which understands every kind of line ending and has no trailing empty item. - Split from the right with
rsplit(). - Reverse operation:
str.join(). - Values are strings. Convert numbers yourself with
int()orfloat(). - Also on
bytesandbytearray.