splitting

str.split

Returns a list of substrings split at each occurrence of sep. If sep is None (default), runs of any whitespace are the separator and leading/trailing whitespace is discarded; if sep is given, empty fields between adjacent separators are preserved.

str.split(sep=None, maxsplit=-1)

Parameters

Parameter Purpose
sep delimiter string; None means any whitespace
maxsplit maximum number of splits (-1 = unlimited)

Examples

>>> 'a b  c'.split()
['a', 'b', 'c']

no sep: any run of whitespace splits, empties discarded

>>> 'a,,b'.split(',')
['a', '', 'b']

explicit sep keeps empty fields

>>> 'a b c d'.split(maxsplit=2)
['a', 'b', 'c d']

maxsplit caps the number of splits

>>> ''.split(',')
['']

empty string with explicit sep returns [''], not []

Gotcha

'a,b,'.split(',') is ['a', 'b', ''] (trailing empty kept). Only split() with no args skips empties. Use splitlines() for newlines.

Related methods

← All Python string methods · Python built-ins