Python example program to split a string at linebreak using splitlines

Python split a string at linebreak using splitlines() :

splitlines() function is used to split a string at line breaks. It returns the list of all lines in the given string. This method takes one parameter. If the parameter is True, line breaks will be included in the result list. Else, line breaks will not be included.
Following are the line boundaries that this method splits :

python splitlines

Syntax of splitlines() :

The syntax of splitlines() method is as below :


The method splitlines() takes one optional parameter keepends. As mentioned above, if we pass True as this parameter, the line breaks will be included in the returned list.

Example of splitlines :

Let’s try to understand how splitlines works with few examples (The source code is available here) :

python splitlines

python splitlines example

Explanation :

1. For str_1, both print methods with or without keepends = True produced the same output. Because str_1 is only a single word.
2. For str_2, both print methods again printed the same output. str_2 is consists of two words but both are separated by a blank space which is not a supported line boundary for splitlines.
3. str_3 contains all supported line boundaries that we have shown above. As you can see that the first print statement separated each word from the string and the second print statement separated the words but added the line boundaries with each one.

Difference between splitlines and split :

1. We can define a separator type in split(). But we can’t define any separator type in splitlines().
2. If we are passing a delimiter string to split(), and if the string is an empty string, it will return one list with an empty string. For example :

python splitlines

You might also like :

Leave a Reply