splitlines() function in Python

In this tutorial, we will learn about splitlines() function in Python.

splitlines() is a built-in function that splits any string based on its line boundaries. It accepts an optional argument keepboundary which is a boolean argument. It has a default value of False. To retain the line boundaries, after the split, set the keepboundary value to True.

The function splitlines() returns a list of the lines. They are in the form of a binary sequence that breaks at ASCII line boundaries. The splitlines() uses the “universal newlines” method for splitting the lines. The line breaks appear in the list depending on the keepboundary value being True.

Syntax:

bytes.splitlines(keepboundary=False)
bytearray.splitlines(keepboundary=False)

The different values that the line boundaries can take are \n, \r, \r\n, \v, \f, \x1c, \x1d, \x1e, etc. \n means line feed. \r means carriage return. \n\r means both line feed and carriage return. \v means line tabulation and can also be represented as \x0b. \f means form feed and can also be denoted as \x0c. \x1c, \x1d and \x1e means file separator, group seperator and record separator respectively.

Sample program to illustrate the use of splitlines() function in Python

s1="Happy Coding folks"
s2=s1.splitlines()
print(s1)
print(s2)
s3="Happy \n Coding \r folks"
s4=s3.splitlines()
print(s4)
s5=s3.splitlines(True)
print(s5)
s6="Happy \f Coding \v folks"
s7=s6.splitlines()
print(s7)
s8=s6.splitlines(True)
print(s8)

Output:

Happy Coding folks
['Happy Coding folks']
['Happy ', ' Coding ', ' folks']
['Happy \n', ' Coding \r', ' folks']
['Happy ', ' Coding ', ' folks']
['Happy \x0c', ' Coding \x0b', ' folks']

This program shows how to use splitlines() in Python in various ways. It also illustrates how keepboundary can take various values of \n, \r, \f or \x0c, \v or \x0b, etc. The output to the above program shows how splitlines() works with varying input values.

String s1 contains a string without any line breaks and then it is used with splitlines() without explicitly setting keepboundary value. It means it will consider the default value which is False. It returns a list that contains the string in s2.

String s3 contains a string with line breaks and then it uses the splitlines() without explicitly setting keepboundary value. It means it will consider the default value which is False. It returns a list that contains the split strings in s4.

String s3 contains a string with line breaks and then it uses the splitlines() with explicitly setting keepboundary value to True. It returns a list that contains the split strings in s5.

The process repeats for string s6 with different line breaks.

Thanks for reading!

Recommended Posts:
String split and join in Python
Split a string on the last occurrence of delimiter or separator in Python

Leave a Reply

Your email address will not be published. Required fields are marked *