Python String splitlines() Method

Short answer
str.splitlines() splits a string at line boundaries and returns a list of the lines, without the line-break characters unless you pass keepends=True.

splitlines() is the right tool for turning multi-line text, such as the content of a file, an email body or a pasted block, into a list of lines. It understands \n, \r\n and \r, so it works on text from any operating system. It also avoids the trailing empty string that split("\n") leaves behind. For splitting on other separators see split().

Quick facts
Syntaxtext.splitlines(keepends=False)
Parameterskeepends (optional): True keeps the line-break characters in each line
ReturnsA list of strings
Empty stringReturns []
Trailing newlineDoes not produce an empty last item

How str.splitlines() breaks text into lines

Each line break ends one line. The break characters themselves are dropped by default, and leading or trailing spaces in a line are kept.

Python
text = "first\nsecond\r\nthird\n"
print(text.splitlines())
print(text.split("\n"))

Compare the two results: splitlines() gives three items, while split("\n") leaves an extra empty string at the end and keeps the \r on the second line.

Keeping the line endings with keepends=True

Pass keepends=True when you need to put the text back together exactly, for example when rewriting a file without changing its line endings.

Python
print("a\nb\r\nc".splitlines(keepends=True))

Which characters count as a line break

Besides the common line endings, splitlines() also splits on a few rarer characters. split("\n") only splits on \n.

CharacterMeaningSplits lines?
\nLine feed (Unix, macOS)Yes
\r\nCarriage return + line feed (Windows)Yes, as one break
\rCarriage return (old Mac)Yes
\v or \x0bVertical tabYes
\f or \x0cForm feedYes
\x85, \u2028, \u2029Next line, line separator, paragraph separatorYes
Space or tabOrdinary whitespaceNo

Examples you can run

Press Run, then edit the code and run it again.

Split a block of text into lines

A triple-quoted string becomes a list of lines.

Split a block of text into lines
notes = """Buy milk
Call Ravi
Pay bill"""
print(notes.splitlines())
print(len(notes.splitlines()))
Expected output['Buy milk', 'Call Ravi', 'Pay bill']
3

Number the lines of a text

Combine splitlines() with enumerate(); see enumerate and zip.

Number the lines of a text
log = "start\nrun\nstop\n"
for n, line in enumerate(log.splitlines(), start=1):
    print(n, line)
Expected output1 start
2 run
3 stop

Skip blank lines and extra spaces

Blank lines come back as empty strings, so filter them out.

Skip blank lines and extra spaces
text = "alpha\n\n  beta  \n\ngamma"
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
print(lines)
Expected output['alpha', 'beta', 'gamma']

Empty string and a single newline

Edge cases that differ from split().

Empty string and a single newline
print("".splitlines())
print("\n".splitlines())
print("".split("\n"))
Expected output[]
['']
['']

Common mistakes

Splitting on \n and getting a stray empty string

✗ Wrong

data = "a\nb\n"
print(data.split("\n"))
Prints `['a', 'b', '']`, with an empty last item.

✓ Right

data = "a\nb\n"
print(data.splitlines())

Use splitlines(), which treats the final newline as the end of the last line.

Expecting whitespace to be stripped

✗ Wrong

print("  a  \n b ".splitlines())
Prints `[' a ', ' b ']`: spaces stay.

✓ Right

print([ln.strip() for ln in "  a  \n b ".splitlines()])

Call strip() on each line.

Expecting blank lines to disappear

✗ Wrong

print("a\n\nb".splitlines())
Prints `['a', '', 'b']`: the blank line is kept as an empty string.

✓ Right

print([ln for ln in "a\n\nb".splitlines() if ln])

Filter with a condition: [ln for ln in lines if ln].

Python String splitlines() Method: questions people ask

How do I split a string into lines in Python?

Call text.splitlines(). It returns a list with one item per line and handles \n, \r\n and \r.

What is the difference between splitlines() and split('\n')?

splitlines() handles all line-break styles and does not add an empty item for a final newline. split("\n") only splits on \n and does.

How do I keep the newline characters when splitting?

Use text.splitlines(keepends=True); each line then keeps its own line-break characters.

Keep learning

Step-by-step lessons:
Python StringsPython String MethodsPython File Handling

Related:
Python String split() MethodPython String strip() MethodHow to Split a String into Words in PythonPython String partition() Method

More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String replace() MethodPython String upper() MethodPython String lower() Method See all →