The splitlines() function in python helps to return a list of lines in the string, here the splitting is done at line breaks. It takes a boolean value as its argument.
str.splitlines([keepends]) #where keepends is a boolean value
The splitlines() function takes a single parameter. By default, line breaks are not provided. The line breaks are also included in items of the list and it may be any of the following.
\n | Line Feed |
\r | Carriage Return |
\r\n | Carriage Return + Line Feed |
\v or \x0b | Line Tabulation |
\f or \x0c | Form Feed |
\x1c | File Separator |
\x1d | Group Separator |
\x1e | Record Separator |
\x85 | Next Line (C1 Control Code) |
\u2028 | Line Separator |
\u2029 | Paragraph Separator |
Parameter | Description | Required / Optional |
---|---|---|
keepends | Specifies if the line breaks should be included (True), or not (False) | Optional |
If line break characters are not given, it returns a list with a single item (a single line).
Input | Return Value |
---|---|
if keepends | a list of lines in the string |
fruits = 'Apple\Orange\r\nBanana\rGrapes'
print(fruits .splitlines())
print(fruits .splitlines(True))
fruits = 'Apple Orange Banana Grapes'
print(fruits.splitlines())
Output:
['Apple', 'Orange', 'Banana', 'Grapes'] ['Apple\n', 'Orange\r\n', 'Banana\r', 'Grapes'] ['Apple Orange Banana Grapes']
string = "Hi How are you\nIam fine.."
output = string.splitlines(True)
print(output)
Output:
['Hi How are you\n', 'Iam fine..']