Sub topic 5
Splitting text into lines with splitlines
This chapter assumes you know how str.split works with a separator, and that you can read short Python scripts and list comprehensions. It covers str.splitlines, the method built for breaking text into lines, and how it differs from split("\n").
Why not just split on "\n"?
Text from files, network responses, and different operating systems ends its lines in different ways. Unix uses \n. Windows uses \r\n. Old Mac files use \r. split("\n") only knows the first. It leaves a stray \r on Windows lines, and it adds an empty string 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']splitlines() recognises all of these endings, removes them, and does not add an empty item for a trailing newline. Like every string method, it returns a new list and leaves the original string unchanged.
How the two methods differ
| Input | `splitlines()` | `split("\n")` |
|---|---|---|
| `""` | `[]` | `['']` |
| `"a\n"` | `['a']` | `['a', '']` |
| `"a\n\nb"` | `['a', '', 'b']` | `['a', '', 'b']` |
| `"a\r\nb"` | `['a', 'b']` | `['a\r', 'b']` |
Two rules explain the table:
- A line ending ends a line. It does not start a new one. So one trailing newline gives no extra item, and empty input gives no lines at all.
- Blank lines in the middle are kept as empty strings. Only a single final terminator is absorbed.
"a\n\n".splitlines()returns['a', ''].
Keeping the line endings
Pass keepends=True (or just True) to leave each terminator attached to its line. This is useful when you need to write the text back exactly as it was.
text = "first\r\nsecond\nthird"
lines = text.splitlines(keepends=True)
print(lines) # ['first\r\n', 'second\n', 'third']
print("".join(lines) == text) # TrueThis gives a lossless round trip. With the default behaviour, "\n".join(text.splitlines()) would turn the \r\n into \n. It would also drop a trailing newline if the original had one.
Filtering and cleaning lines
A common pattern is to split, strip each line, and skip the blank ones.
text = "name: Ada\r\n\r\n name: Grace \n"
cleaned = [line.strip() for line in text.splitlines() if line.strip()]
print(cleaned) # ['name: Ada', 'name: Grace']Calling strip() twice is fine for short inputs. For a large input, compute it once per line with a generator or an assignment expression.
A gotcha: more line boundaries than you expect
splitlines treats more characters as line boundaries than \n, \r, and \r\n. The full list includes vertical tab (\v), form feed (\f), the file, group, and record separators (\x1c to \x1e), next line (\x85), and the Unicode line and paragraph separators (\u2028, \u2029).
odd = "a\x0cb\u2028c"
print(odd.splitlines()) # ['a', 'b', 'c']
print(odd.split("\n")) # ['a\x0cb\u2028c']Most text never contains these characters. If your data might, for example text copied from a PDF or a web page, and you only want to break on real newlines, use split("\n") and handle \r yourself. Pick the method that matches the rule your data format actually uses.
splitlines and files
Text files opened with open() in default text mode translate \r\n and \r to \n as they are read. Iterating over the file gives lines that still end in \n. Calling read().splitlines() gives lines without endings. Choose by whether you want the terminators.
with open("notes.txt", encoding="utf-8") as f:
lines = f.read().splitlines()For very large files, iterate over the file object instead. read() loads the whole file into memory.
Choosing a method
Exercise
What does "x\n\ny\r\n".splitlines() return, and what does "x\n\ny\r\n".split("\n") return?
Show answer
splitlines() returns ['x', '', 'y']. The blank line in the middle is kept, and the final \r\n ends the last line without adding an item. split("\n") returns ['x', '', 'y\r', '']. It leaves the \r on the last line and adds an empty string after the final newline.
Exercise
You read a text file with \r\n line endings and must write it back unchanged after editing one line. Which splitlines argument helps, and how do you rebuild the text?
Show answer
Use splitlines(keepends=True). Replace the one line you are editing, keeping its original ending, then rebuild the text with "".join(lines).