splitting
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.splitlines(keepends=False) Parameters
| Parameter | Purpose |
|---|---|
| keepends | if True, keep line terminators in the resulting substrings |
| returns | list[str] of lines (empty list for empty input) |
Examples
>>> 'a\nb\nc'.splitlines()
['a', 'b', 'c'] one item per line
>>> 'a\nb\n'.splitlines()
['a', 'b'] trailing newline does NOT create an empty item (unlike split('\n'))
>>> 'a\r\nb\rc'.splitlines()
['a', 'b', 'c'] handles \r, \n, and \r\n uniformly
>>> 'a\nb\n'.splitlines(keepends=True)
['a\n', 'b\n'] keepends preserves line terminators
Gotcha
Behaves differently from split('\n') at the tail: 'a\n'.splitlines() is ['a'], while 'a\n'.split('\n') is ['a', ''].
Related methods
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.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.