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 :
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) :
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 :
You might also like :
- Python swap case of each character of a string
- Python program to pad zeros to a string
- Python tutorial to calculate the sum of two string numbers
- Python program to convert a string to an integer
- Python program to capitalize first letter of each words of a string
- Python program to find larger string among two strings