logo

Python String Splitlines() Method


Show

Description

The splitlines() method in Python string returns a list with all the lines present in the string, optionally which is inclusive of the line breaks (in case if num is supplied and also if it is true) Python string splitlines() method thus splits the string depending on the lines. It breaks the string over the line boundaries and also returns a list of strings split. ... A table of the line breakers is thus given below that split the string. This method further splits on the specifically given line boundaries.

Syntax

Here is the syntax for the splitlines() method:

str.splitlines()

Parameters

  • Keepends - This refers to an optional parameter and if its value is true, then the line breaks and the needs are also included into the output.

Example

The example below shows the usage of splitlines() method in Python string.

#!/usr/bin/python

str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines( )
print str.splitlines( 0 )
print str.splitlines( 3 )
print str.splitlines( 4 )
print str.splitlines( 5 )

When the above program is run, it produces the following result:

['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']

Example

If you pass True as the required parameter to this python string method then this includes the line breaks within the output.

#!/usr/bin/python

str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines(True)
print str.splitlines( 0 )
print str.splitlines( 3 )
print str.splitlines( 4 )
print str.splitlines( 5 )

Output

When the above program is run, then it produces the following result:

['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.