Python String splitlines() Method
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().
| Syntax | text.splitlines(keepends=False) |
|---|---|
| Parameters | keepends (optional): True keeps the line-break characters in each line |
| Returns | A list of strings |
| Empty string | Returns [] |
| Trailing newline | Does 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.
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.
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.
| Character | Meaning | Splits lines? |
|---|---|---|
\n | Line feed (Unix, macOS) | Yes |
\r\n | Carriage return + line feed (Windows) | Yes, as one break |
\r | Carriage return (old Mac) | Yes |
\v or \x0b | Vertical tab | Yes |
\f or \x0c | Form feed | Yes |
\x85, \u2028, \u2029 | Next line, line separator, paragraph separator | Yes |
| Space or tab | Ordinary whitespace | No |
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.
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.
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.
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().
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"))✓ 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())✓ 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())✓ 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 →