splitlines() cuts a string at its line breaks and returns the lines as a list of strings. It understands the common endings: \n (Unix), \r\n (Windows), and a few rarer ones.
The line break characters are removed unless you pass keepends=True. A final newline does not create an extra empty line at the end, which is the main difference from split() with "\n". The original string is not changed.
text.splitlines() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Call it with no arguments, or pass True to keep the line breaks.
The default. The line breaks are removed from the lines.
keepends. With True, each line ends with its \n.
A keyword works too.keepends=True and the plain True give the same list.
A round trip. Joining the lines with an empty separator rebuilds the original text exactly.
Example 3 — Print Numbered Lines
Loop over the lines with enumerate(), and see how an empty line is kept.
python
notes = "milk\n\neggs\nbread\n"
for number, line in enumerate(notes.splitlines(), 1):
print(number, repr(line))
Output
1 'milk'
2 ''
3 'eggs'
4 'bread'
How It Works
A list to loop over.splitlines() returns the lines, so a for loop can visit each one.
Count from 1.enumerate(..., 1) starts the numbers at 1 instead of 0.
The blank line stays. The empty line between milk and eggs is item 2, shown as an empty string.
No extra line at the end. The final newline does not produce a fifth item.
Frequently Asked Questions
It splits a string at its line breaks and returns a list of the lines, without the line break characters unless keepends is True.
splitlines() also handles \r\n and other line breaks, and it does not add an empty string for a final newline. split("\n") cuts only at \n and does add that empty string.
Pass True, as in text.splitlines(True), or use the keyword keepends=True.
Yes. A blank line in the middle of the text becomes an empty string in the list. Only the final newline is not counted as an extra line.
Use "\n".join(lines). If you used keepends=True, use "".join(lines) instead.