String method

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.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
keepends
optional, 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

Pythoneditable
text = "first\nsecond\nthird"
print(text.splitlines())
Output
['first', 'second', 'third']

2splitlines() vs split("\n")

Pythoneditable
text = "a\r\nb\r\n"
print(text.split("\n"))
print(text.splitlines())
Output
['a\r', 'b\r', '']
['a', 'b']

Windows line breaks and the final new line leave junk with split("\n").

3Keep the line breaks

Pythoneditable
print("one\ntwo\n".splitlines(keepends=True))
Output
['one\n', 'two\n']

4Number the lines of a file

Pythoneditable
with open("poem.txt") as f:
    text = f.read()
for n, line in enumerate(text.splitlines(), start=1):
    print(n, line)
Output
1 Roses are red
2 Violets are blue
3 Python is fun

5Count non-empty lines

Pythoneditable
notes = """buy milk

call Lena

pay rent
"""
lines = [l for l in notes.splitlines() if l.strip()]
print(len(lines), "tasks")
Output
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.

Pythoneditable
data = "a,b\nc,d"
print(data.splitlines())
print([line.split(",") for line in data.splitlines()])
Output
['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 [''].

Spotted a mistake on this page? Tell us