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)
Parameter | Condition | Description |
keepends | Required | If set to TRUE, line breaks are included in the resulting list |
Basic Example
# Split a string at '\n' into a list
S = 'First line\nSecond line'
x = S.splitlines()
print(x)
# Prints ['First line', 'Second line']
Different Line breaks
Newline \n
, carriage return \r
and form feed \f
are common examples of line breaks.
S = 'First\nSecond\r\nThird\fFourth'
x = S.splitlines()
print(x)
# Prints ['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.
S = 'First line\nSecond line'
x = S.splitlines(True)
print(x)
# Prints ['First line\n', 'Second line']
splitlines() vs split() on Newline
There are mainly two differences:
1. Unlike split(), splitlines() returns an empty list for the empty string.
# splitlines()
S = ''
x = S.splitlines()
print(x)
# Prints []
# split()
S = ''
x = S.split('\n')
print(x)
# Prints ['']
2. When you use splitlines()
a terminal line break does not result in an extra line.
# splitlines()
S = 'One line\n'
x = S.splitlines()
print(x)
# Prints ['One line']
# split()
S = 'One line\n'
x = S.split('\n')
print(x)
# Prints ['One line', '']