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.
Here is the syntax for the splitlines() method:
str.splitlines()
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']
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 )
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.