Skip to content
Tutorials Center
My learning

Topics

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.

Python
print("a\nb\r\nc".splitlines())   # ['a', 'b', 'c']

Try it

Python Splitting lines

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.

Python Processing a block of text

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

Python
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=True lets 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 csv module.
  • Also on bytes and bytearray, where only \n, \r and \r\n count.