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
str.splitlines
Splits the string at universal line boundaries (\n, \r, \r\n, and other Unicode line terminators). Unlike split('\n'), it does not produce a trailing empty string when the input ends with a newline.
str.partition
Splits the string at the first occurrence of sep and returns a 3-tuple (before, sep, after). If sep is not found, returns (original, '', '') — so unpacking is always safe.
str.join
Returns a string built by concatenating every string in the iterable, separated by the string on which join is called. Every element of the iterable must be a str, or TypeError is raised.