String splitlines() method splits a string into a list, based on line breaks in Python. Line breaks are not included in the resulting strings unless explicitly requested.
The above figure describes that we split the input string at the line break character and converted it into a list of three elements.
quote_string = "I don’t play the odds\nI play the man\nHarvey Specter" output_list = quote_string.splitlines() print(output_list) # Output: ['I don’t play the odds', 'I play the man', 'Harvey Specter']
The line break character is represented by “\n, \r, \r\n, \v, \f”. That means, if the interpreter finds these characters, it will split from that point and return the list of splitted elements.
Syntax
str.splitlines(keepends=False)
Parameters
Argument | Description |
keepends (bool, optional) | If you pass this argument to True, the line break characters (\n, \r, etc.) are retained.
By default, its value is False. |
Keeping line endings
You can keep the line break characters in the output list by passing keepends = True.
stock = "National\nSecurities\nDepository\nLimited" output_with_line_break = stock.splitlines(keepends=True) print(output_with_line_break) # Output: ['National\n', 'Securities\n', 'Depository\n', 'Limited']
Mixed line separators
Let’s use a string with different types of separators
input_with_diff = "M1\rL2\nB3\r\nZ4" print(input_with_diff.splitlines()) # Output: ['M1', 'L2', 'B3', 'Z4']
It ensures consistent line splitting regardless of the newline format.
Single line (No Newlines)
If no break line character exists in the input string, it returns a list with a single element.
single_line = "NarendraModi" print(single_line.splitlines()) # Output: ['NarendraModi']
Empty string
An empty string returns an empty list.
empty_text = "" print(text.splitlines()) # Output: []
Vertical Tab and Form Feed
The \v → Vertical tab (U+000B) and \f → Form feed (U+000C) are less-known line break characters, but str.splitlines() recognizes them as line boundaries.
text = "Line1\vLine2\fLine3" print(text.splitlines()) # Output: ['Line1', 'Line2', 'Line3']
That’s all!