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

← All Python string methods · Python built-ins