Sub topic 5
Splitting text into lines with splitlines
This chapter assumes you know basic Python syntax and can use the REPL. It also assumes you have used str.split and know that strings are immutable, so every string method returns a new value. By the end you will know what splitlines treats as a line break, how it differs from split("\n"), and when each is the right choice.
Why a separate method for lines
Text rarely comes with one tidy line ending. A file written on Linux uses \n, one written on old Windows tools uses \r\n, and classic Mac OS files use a lone \r. Text pasted from the web can contain other separators too.
You can split on "\n" with split, but then you have to deal with leftover \r characters and an empty last item. str.splitlines is built for this job. It recognises all the common line boundaries and does not invent an empty item after a final newline.
data = "one\ntwo\r\nthree\n"
print(data.splitlines()) # ['one', 'two', 'three']
print(data.split("\n")) # ['one', 'two\r', 'three', '']
print(data.splitlines(True)) # ['one\n', 'two\r\n', 'three\n']split("\n") leaves a \r on 'two\r' and produces a final ''. splitlines() returns three clean lines. Passing True as the keepends argument keeps each terminator attached to its line.
The method's signature and result
str.splitlines(keepends=False)- It returns a new list of strings. The original string is unchanged.
- With
keepends=False(the default), the line terminators are removed. - With
keepends=True, each line keeps its own terminator exactly as it appeared, so\r\nstays\r\n. - You can pass the argument by keyword, which is clearer than a bare
True:data.splitlines(keepends=True).
What counts as a line boundary
For str, splitlines splits at more than just \n. This table lists the boundaries.
| Sequence | Name | Splits in `str` | Splits in `bytes` |
|---|---|---|---|
| `\n` | line feed | yes | yes |
| `\r` | carriage return | yes | yes |
| `\r\n` | carriage return plus line feed | yes, as one boundary | yes, as one boundary |
| `\v` or `\x0b` | line tabulation | yes | no |
| `\f` or `\x0c` | form feed | yes | no |
| `\x1c`, `\x1d`, `\x1e` | file, group and record separators | yes | no |
| `\x85` | next line | yes | no |
| `\u2028` | line separator | yes | no |
| `\u2029` | paragraph separator | yes | no |
The pair \r\n counts as a single boundary. You never get an empty line between the \r and the \n.
text = "a\u2028b\x0cc\x1dd\x85e"
print(text.splitlines()) # ['a', 'b', 'c', 'd', 'e']
print(text.split("\n")) # ['a\u2028b\x0cc\x1dd\x85e']
raw = b"a\x0bb\nc"
print(raw.splitlines()) # [b'a\x0bb', b'c']The bytes version only recognises \n, \r and \r\n. This is a common source of surprise when the same logic works on str but behaves differently after you switch to bytes.
Empty strings and trailing newlines
The main difference from split("\n") is how the end of the input is treated. splitlines treats a terminator as ending a line. split treats a separator as sitting between two items, so a trailing separator gives an empty last item.
print("a\n".splitlines()) # ['a']
print("a\n".split("\n")) # ['a', '']
print("".splitlines()) # []
print("".split("\n")) # ['']
print("\n".splitlines()) # ['']
print("a\n\n".splitlines()) # ['a', '']
print("a\n\nb".splitlines()) # ['a', '', 'b']These cases follow from one rule: a line is some text followed by an optional terminator.
- The empty string has no lines, so the result is an empty list.
"".split("\n")returns['']because splitting always yields at least one item. - A lone
"\n"is one empty line, so the result is['']. - Blank lines in the middle of the text are kept as
''. - Only the very last terminator is absorbed.
"a\n\n"has two lines,'a'and''.
The empty-input difference matters when you count lines. len(text.splitlines()) gives the number of lines a person would count. len(text.split("\n")) gives one more whenever the text ends with a newline.
for text in ["", "x", "x\n", "x\ny", "x\ny\n"]:
print(repr(text), len(text.splitlines()), len(text.split("\n")))This prints:
'' 0 1
'x' 1 1
'x\n' 1 2
'x\ny' 2 2
'x\ny\n' 2 3Keeping the line endings
With keepends=True, joining the pieces gives back the original text exactly. That makes it the right choice when you need to rewrite part of a file without changing its line endings.
text = "alpha\r\nbeta\ngamma"
lines = text.splitlines(keepends=True)
print(lines) # ['alpha\r\n', 'beta\n', 'gamma']
print("".join(lines) == text) # TrueCompare this with the version that drops the endings:
lines = text.splitlines()
print("\n".join(lines) == text) # FalseJoining with "\n" converts the \r\n into \n, and it cannot tell whether the original ended with a newline. splitlines() does not record which terminator was used, so information is lost.
Practical patterns
Number the lines
enumerate with start=1 gives the line numbers a human expects.
report = "name,score\nada,90\n\ngrace,95\n"
for number, line in enumerate(report.splitlines(), start=1):
print(f"{number}: {line!r}")The output is:
1: 'name,score'
2: 'ada,90'
3: ''
4: 'grace,95'The blank third line keeps its number, which is what you want when reporting errors back to a user.
Skip blank lines
Because blank lines are kept as empty strings, filter them out explicitly. Calling strip() also removes lines that contain only spaces.
report = "name,score\nada,90\n \ngrace,95\n"
rows = [line for line in report.splitlines() if line.strip()]
print(rows) # ['name,score', 'ada,90', 'grace,95']Normalise line endings
To convert any mixture of endings into \n, split and join again. The function below also makes sure a non-empty result ends with one newline.
def normalize_newlines(text: str) -> str:
lines = text.splitlines()
if not lines:
return ""
return "\n".join(lines) + "\n"
print(repr(normalize_newlines("a\r\nb\rc"))) # 'a\nb\nc\n'
print(repr(normalize_newlines(""))) # ''Work with text read from a file
Files opened in text mode with the default settings already translate \r\n and \r to \n while reading. This is called universal newlines. Each approach below has different costs.
from pathlib import Path
path = Path("notes.txt")
path.write_text("first\nsecond\nthird\n", encoding="utf-8")
# Reads the whole file into memory, then splits.
lines = path.read_text(encoding="utf-8").splitlines()
print(lines) # ['first', 'second', 'third']
# Streams one line at a time, and keeps the "\n" on each line.
with path.open(encoding="utf-8") as f:
for line in f:
print(repr(line)) # 'first\n', then 'second\n', then 'third\n'Use read_text().splitlines() when the file is small and you want a list of clean lines. Iterate over the file object when the file may be large, and strip the newline yourself with line.rstrip("\n").
Common mistakes
- Using
split("\n")on data from unknown sources. Windows-style input leaves\rat the end of every item. Comparisons such asline == "done"then fail with no visible clue, because'done\r'prints likedone. - Forgetting that
splitlinesreturns[]for an empty string. Code likelines = text.splitlines(); first = lines[0]raisesIndexErroron empty input. Checkif lines:first. - Expecting the terminator style to survive. Without
keepends=True, you cannot restore the original endings. - Passing a separator.
splitlinestakes no separator.text.splitlines("\n")does not mean "split on\n". The first argument iskeepends, so a non-empty string is treated as true and the terminators are kept. - Assuming
bytesandstragree. Thebytesmethod recognises only three boundaries, so data containing\x0csplits differently after decoding.
print("a\nb".splitlines("\n")) # ['a\n', 'b'] (the string counted as True)Choosing between splitlines and split
| Situation | Better choice | Reason |
|---|---|---|
| Text from files, users or the network, with unknown endings | `splitlines()` | Handles `\n`, `\r\n` and `\r`, and has no empty last item |
| Format defines a line as ending only at `\n` | `split("\n")` | Does not cut at `\x0c`, `\u2028` and similar characters |
| Need to rebuild the exact original | `splitlines(keepends=True)` | Joining the parts restores the text |
| Count lines the way an editor does | `len(text.splitlines())` | A trailing newline does not add a line |
| Large file, one line at a time | Iterate over the file | Does not load the whole file into memory |
Exercise
What does each of these expressions return: "x\r\ny\n\n".splitlines() and "x\r\ny\n\n".split("\n")? Then say which one you would use to count the lines in a text file, and why.
Show answer
"x\r\ny\n\n".splitlines() returns ['x', 'y', '']. The \r\n is a single boundary, the first \n ends 'y', and the last \n ends an empty line. "x\r\ny\n\n".split("\n") returns ['x\r', 'y', '', ''], which keeps the \r and adds an empty final item. For counting lines, use len(text.splitlines()), because it gives the count a person or editor would report (3 here) and is not inflated by the trailing newline.
Exercise
Write a function non_blank_lines(text) that returns the lines of text with their original endings kept, skipping lines that contain only whitespace. What does it return for "a\r\n \nb"?
Show answer
Use splitlines(keepends=True) and filter with strip():
def nonblanklines(text):
return [line for line in text.splitlines(keepends=True) if line.strip()]
For "a\r\n \nb" it returns ['a\r\n', 'b']. The middle line ' \n' is dropped because stripping it leaves an empty string, and 'a\r\n' keeps its \r\n ending.