Python Reference ยท String Methods
Python str.splitlines() method
Reference for Python str.splitlines(): split text into a list of lines at any line boundary, the keepends option, trailing newlines and how it beats split().
The str.splitlines() method splits a string at line boundaries and returns the lines as a list. It recognizes \n, \r\n and \r, plus a few rarer Unicode separators, so it works on text from any platform.
Unlike split("\n"), it does not produce an extra empty string when the text ends with a newline, and it handles Windows line endings correctly.
print("a\nb\r\nc".splitlines()) # ['a', 'b', 'c']
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.splitlines() str.splitlines(keepends=False)
| Name | Description |
|---|---|
keepends |
Optional. If true, each line keeps its line ending. The default is False. |
Return value: a list of strings.
Raises: TypeError if keepends is not a valid argument type.
Usage notes
- Recognized boundaries include
\n,\r,\r\n, vertical tab\v, form feed\f,\x1c,\x1d,\x1e,\x85,โจandโฉ. If your data can contain form feeds or similar characters, they will split lines too. - No trailing empty item.
"a\n".splitlines()is['a'], while"a\n".split("\n")is['a', '']. - Blank lines are kept in the middle:
"a\n\nb"gives['a', '', 'b']. - Empty string gives
[], a lone newline gives['']. keepends=Truelets you rebuild the exact text with"".join(lines).- Reading files: iterating over a text file already yields lines, each ending in
\n;file.read().splitlines()gives them without endings. - Not for CSV. Quoted fields can contain newlines; use the
csvmodule. - Also on
bytesandbytearray, where only\n,\rand\r\ncount.
Related
str.split(),str.rstrip(),str.strip(),str.join()- Lessons: Strings, String methods