Python String splitlines() Method

Splits a string at line breaks

Usage

The splitlines() method splits a string at line breaks and returns them in a list.

If the optional keepends argument is specified and TRUE, line breaks are included in the resulting list.

Syntax

string.splitlines(keepends)

Python string splitlines() method parameters
ParameterConditionDescription
keependsRequiredIf set to TRUE, line breaks are included in the resulting list

Basic Example

Example: Split a string at ‘\n’ into a list

S = 'First line\nSecond line'
x = S.splitlines()
print(x)	# ['First line', 'Second line']

Different Line breaks

Newline \n, carriage return \r and form feed \f are common examples of line breaks.

Example: Using several different line breaks

S = 'First\nSecond\r\nThird\fFourth'
x = S.splitlines()
print(x)	# ['First', 'Second', 'Third', 'Fourth']

Keep Line Breaks in Result

If the optional keepends argument is specified and TRUE, line breaks are included in the resulting list.

Example:

S = 'First line\nSecond line'
x = S.splitlines(True)
print(x)	# ['First line\n', 'Second line']

splitlines() vs split() on Newline

There are mainly two differences:

Unlike split(), splitlines() returns an empty list for the empty string.

Example:

S = ''
x = S.splitlines()
print(x)    # []
S = ''
x = S.split('\n')
print(x)    # ['']

When you use splitlines() a terminal line break does not result in an extra line.

Example:

S = 'One line\n'
x = S.splitlines()
print(x)    # ['One line']
S = 'One line\n'
x = S.split('\n')
print(x)    # ['One line', '']