Tutorial Study Image

Python splitlines()

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
 

splitlines() Parameters:

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

splitlines() Return Value

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

 

Examples of splitlines() method in Python

Example 1: How splitlines() works in Python?


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']

Example 2: Working of splitlines() in Python


string = "Hi How are you\nIam fine.."

output = string.splitlines(True)

print(output)
 

Output:


['Hi How are you\n', 'Iam fine..']