Python String splitlines() Method

The splitlines() method splits a string at line boundaries (such as \n, \r, or \n\r) and returns a list of lines (as substrings) in the string.

Syntax

string.splitline(keepends)

Parameter

keepends (Optional): If True, line breaks are included in the resulting list. Default is False.

Return Value

Returns a list of lines (as substrings) in the list.

Examples

Without Keeping Line Breaks

text = "Python\nis\nawesome"
lines = text.splitlines()
print(lines) # Output: ['Python', 'is', 'awesome']

Keeping Line Breaks

If you want to keep line breaks in the resulting list, you can set the keepends parameter to True.

text = "Python\nis\nawesome"
lines = text.splitlines(True)
print(lines) # Output: ['Python\n', 'is\n', 'awesome']

Multi-Line String

text = """Python
is
awesome"""
lines = text.splitlines()
print(lines) # Output: ['Python', 'is', 'awesome']

Line Boundaries

The splitlines() method splits at the following line boundaries:

Escape SequenceName
\nLine Feed
\rCarriage Return
\r\nCarriage Return + Line Feed
\v or \x0bLine Tabulation
\f or \x0cForm Feed
\x1cFile Separator
x1dGroup Separator
x1eRecord Separator
\x85Next Line (C1 Control Code)
\u2028Line Separator
\u2029Paragraph Separator