str.splitlines()
Split a string into lines using universal newlines — the safer, cross-platform alternative to split("\n").
Demo
splitlines recognizes many line separators — \n, \r, \r\n, plus rarer ones like \x0b, \x0c, \x1c, \x1d, \x1e, \x85, \u2028, \u2029. Unlike split("\n"), a trailing newline does NOT produce a final empty string. When keepends=True, each line keeps the terminator that ended it — round-trippable back to the original.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| keepends | bool | no (False) | If True, keep the line terminator on each line. Useful for round-tripping — "".join(text.splitlines(True)) equals text. |
Return value
list[str] — A list of the lines. Line terminators are stripped by default; keepends=True keeps them attached. A trailing newline does NOT produce a final empty string.
Common patterns
for line in text.splitlines(): process(line)
kept = [ln for ln in text.splitlines(True) if not ln.startswith("#")] filtered = "".join(kept)
normalized = "\n".join(text.splitlines())
Examples
Pitfalls
"a\nb\n".split("\n")
"a\nb\n".splitlines()
"ab\vcd".splitlines()
"ab\vcd".split("\n")
"a\r\nb".split("\n")
"a\r\nb".splitlines()
"\n".join("a\nb\n".splitlines(True))
"".join("a\nb\n".splitlines(True))
When to use
- Reading lines from files or network text
- Any text where line endings might vary
- Round-trip-safe filtering (with keepends=True)
- Normalizing mixed line endings
- You need the trailing empty string as a signal → split("\n")
- You want to split on a DIFFERENT delimiter → split(delim)
- You have obscure control characters as data → split("\n") is safer
- Streaming very large text without loading all of it → iterate the file object
Notes
FAQ
It treats a terminal line break as the terminator of the last line, not the start of a new empty line — matching how humans read text files. split("\n") does the opposite: any newline creates a boundary, so a trailing one leaves an empty tail.