The String splitlines() method splits a string at line breaks (like \n, \r, or \r\n) and returns them in a list.
Syntax
my_string.splitlines(keepends)splitlines() Parameters
Python String splitlines() method parameters:
| Parameter | Condition | Description |
|---|---|---|
keepends |
Optional | If set to True, line breaks are included in the resulting list |
splitlines() Return Value
Python String splitlines() method returns a list of strings, each corresponding to a line in the original multi-line string.
If keepends parameter is set to True, line breaks are included in the resulting list.
Examples
Example 1: Splits a String at line breaks with splitlines()
The splitlines() method splits a string at line breaks and returns them in a list.
In this example, the string is splitted at line break \n:
my_str = 'First Line\nSecond Line'
result = my_str.splitlines()
print(result) # Output: ['First Line', 'Second Line']output
['First Line', 'Second Line']Example 2: Splits a String at different line breaks with splitlines()
Newline \n, carriage return \r and form feed \f are common examples of line breaks that splitlines() method can use to split lines.
my_str = 'One\nTwo\rThree\fFour'
result = my_str.splitlines()
print(result) # Output: ['One', 'Two', 'Three', 'Four']output
['One', 'Two', 'Three', 'Four']Example 3: Splits a Multi Line String at line breaks with splitlines()
We can also split the lines from multi line strings using the splitlines() method.
my_str = '''One
Two
Three
Four
'''
result = my_str.splitlines()
print(result) # Output: ['One', 'Two', 'Three', 'Four']output
['One', 'Two', 'Three', 'Four']Example 4: Splits a String keep line breaks in the result
If the optional keepends argument is specified with value True, then line breaks are included in the resulting list.
my_str = 'One\nTwo\rThree'
result = my_str.splitlines(True)
print(result) # Output: ['One\n', 'Two\r', 'Three']output
['One\n', 'Two\r', 'Three']splitlines() method vs split() method on Newline
Two main differences between splitlines() and split() are about the empty string and single line with a terminal line break.
Empty String with splitlines() and split()
splitlines()returns an empty list for the empty string.split()returns a list with a single item that is an empty string.
my_str = ''
result = my_str.splitlines()
print(result) # Output: []
my_str = ''
result = my_str.split('\n')
print(result) # Output: ['']output
[]
['']Single Line with splitlines() and split()
When you use splitlines() method, a terminal line break does not result in an extra line.
my_str = 'Single Line\n'
result = my_str.splitlines()
print(result) # Output: ['Single Line']
my_str = 'Single Line\n'
result = my_str.split('\n')
print(result) # Output: ['Single Line', '']output
['Single Line']
['Single Line', '']