Open In App

Python String splitlines() method

Last Updated : 18 Nov, 2025
Comments
Improve
Suggest changes
21 Likes
Like
Report

The splitlines() method is used to split a string into a list of lines. It separates the string wherever it finds line-break characters such as \n, \r, or \r\n. This method is helpful when working with multi-line text, logs, or any data that needs to be processed line by line.

Example 1: This example shows how splitlines() separates a multi-line string into individual lines by detecting newline characters.

Python
s = "Alpha\nBeta\nGamma"
res = s.splitlines()
print(res)

Output
['Alpha', 'Beta', 'Gamma']

Explanation: s.splitlines() splits the string at each \n and removes the newline characters.

Syntax

string.splitlines(keepends=False)

Parameters: keepends(optional) - Boolean value.

  • True: keeps newline characters in output.
  • False: removes newline characters (default).

Example 2: This example uses the keepends=True argument so each returned line includes its newline character.

Python
s = "Line1\nLine2\nLine3\n"
res = s.splitlines(keepends=True)
print(res)

Output
['Line1\n', 'Line2\n', 'Line3\n']

Explanation: splitlines(keepends=True) keeps \n at the end of each list element.

Example 3: This example demonstrates how splitlines() behaves when the string contains blank lines it returns empty strings for those positions.

Python
s = "One\n\nTwo\n\nThree"
res = s.splitlines()
print(res)

Output
['One', '', 'Two', '', 'Three']

Explanation: Blank lines between newline characters become empty strings ('') in the result.


Explore