str.splitlines()
Splits a text into a list of lines at every line break, whether it is written as \n, \r\n or \r, without an empty last line.
str.splitlines(keepends=False)splitlines() breaks a text into its lines and returns them as a list. It understands every kind of line break: \n (Linux and macOS), \r\n (Windows) and a few rarer ones.
It is the cleanest way to work line by line with text you already have in a string, such as the contents of a file or a multi-line string.
It differs from split("\n") in a helpful way: a final line break does not create an empty string at the end, and Windows \r characters do not stay stuck to your lines.
Parameters
| Parameter | What it is |
|---|---|
keependsoptional, default False | If True, each line keeps its line break at the end. |
Return value
A new list of strings, one per line.
Examples
1Split into lines
text = "first\nsecond\nthird"
print(text.splitlines())['first', 'second', 'third']
2splitlines() vs split("\n")
text = "a\r\nb\r\n"
print(text.split("\n"))
print(text.splitlines())['a\r', 'b\r', ''] ['a', 'b']
Windows line breaks and the final new line leave junk with split("\n").
3Keep the line breaks
print("one\ntwo\n".splitlines(keepends=True))['one\n', 'two\n']
4Number the lines of a file
with open("poem.txt") as f:
text = f.read()
for n, line in enumerate(text.splitlines(), start=1):
print(n, line)1 Roses are red 2 Violets are blue 3 Python is fun
5Count non-empty lines
notes = """buy milk
call Lena
pay rent
"""
lines = [l for l in notes.splitlines() if l.strip()]
print(len(lines), "tasks")3 tasks
Common mistakes
Expecting splitlines() to split at a separator
splitlines() takes no separator; its only argument is keepends. Use str.split() to cut at commas or other text.
data = "a,b\nc,d"
print(data.splitlines())
print([line.split(",") for line in data.splitlines()])['a,b', 'c,d'] [['a', 'b'], ['c', 'd']]
Questions people ask
How do I read a file as a list of lines without new lines?
f.read().splitlines(). A loop over f with line.rstrip("\n") does the same while reading line by line.
Why does split("\n") give an empty string at the end?
Because the text ends with \n, and split() keeps the empty piece after it. splitlines() does not.
What does splitlines() return for an empty string?
An empty list []. "".split("\n") gives [''].