Python String splitlines() Method

The splitlines() method splits the string at line boundaries and returns a list of lines in the string. Line breaks are not included in the list unless keepends parameter is specified as True.

Syntax:

str.splitlines(keepends)

Parameters:

keepends: (optional) Set True in linebreaks should be included otherwise False. Default is False

Return Value:

A list object with all the lines.

The following characters are considered as line boundary:

Line Boundaries Char Description
\n Line Feed
\r Carriage Return
\n\r 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

The following examples demonstrates the simple use of the splitlines() method.

Example:
mystr = '''Python
is a
programming language'''
print(mystr.splitlines())
Output
['Python', 'is a', 'programming language']

In the above example, triple ''' is used to define a multi-line string. It uses \n as a line boundary by default. So, the splitlines() will split at each line break and return a list of lines as string elements. We have not specified the keepends parameters, which defaults to False and so does not include \n in each element.

The following examples specifies the keepends parameter to True, and so includes \n in the list.

Example:
mystr = '''Python
is a
programming language'''
print(mystr.splitlines(True))
Output
['Python\n', 'is a\n', 'programming language']

The splitlines() method will a string with any of the line boundary specified in the table above.

Example:
langs = 'C#\rPython\rJava\rSQL\rHadoop' # \r as line boundary
print(langs.splitlines())
langs = 'C#\vPython\vJava\vSQL\vHadoop' # \v as line boundary
print(langs.splitlines())
langs = 'C#\x1dPython\x1dJava\x1dSQL\x1dHadoop' # \x1d as line boundary
print(langs.splitlines())
Output
['C#', 'Python', 'Java', 'SQL', 'Hadoop']
['C#', 'Python', 'Java', 'SQL', 'Hadoop']
['C#', 'Python', 'Java', 'SQL', 'Hadoop']

The splitlines() method also takes integer values as its parameters where 0 is False, and the rest of the numerical values (positive and negative) are True.

Example:
langs = 'C#\rPython\rJava\rSQL\rHadoop' # \r as line boundary
print(langs.splitlines(0))
print(langs.splitlines(1)) # keeps line breaks
Output
['C#', 'Python', 'Java', 'SQL', 'Hadoop']
['C#\r', 'Python\r', 'Java\r', 'SQL\r', 'Hadoop']

The splitlines() method returns an empty list for an empty string and if a string does not contain a line boundary then returns a list with the whole string as a single element, as shown below.

Example:
mystr = ''
print(mystr.splitlines())

langs = 'Hello World' 
print(langs.splitlines())
Output
[]
['Hello World']
Want to check how much you know Python?