Today in this tutorial we will discuss the Python string splitlines () method. First, let’s take a look at the main method definition.
What is the String splitlines () method in Python?
splitlines () &it is a built-in method that returns a list of strings in a string, with a break at the line boundaries. Line breaks are not included in the resulting list unless
keepends is specified as true.
- str &the string object that we need to split into a list of strings,
- keepends, when
Trueis set, the line boundaries are included in the resulting list items. Otherwise, no line breaks are included.
A table for line break characters and their corresponding descriptions are shown below.
Line break table
|rn||Carriage return + line feedtr>|
|v or x0b||Tabbing strings (Python 3.2 and later)|
|f or x0c||Form Submission (Python 3.2 and later)|
|x1d td >||Group Separator|
|x85||Next line (C1 check code)|
As mentioned before, without mentioning the parameter keepends will generate a list of split lines excluding line breaks or boundary characters.
Take a look at the example below.
# String initialisation string1 =" Tim Charlie John Alan "string2 =" Welcome to AskPython! " string3 = "Keyboardu2028Monitoru2029x1cMousex0cCPUx85Motherboardx1eSpeakers UPS" #without keepends print (string1.splitlines ()) print (string2.splitlines ()) print (string3.splitlines ())
[’Tim’,’ Charlie’, ’John’,’ Alan’] [’Welcome’,’ ’,’ to’, ’AskPython!’] [’Keyboard ’,’ Monitor’, ’’, ’Mouse’,’ CPU’, ’Motherboard’,’ Speakers’, ’UPS’]
- We have announced three lines containing different words, separated by different line breaks,
- We pass each one to the inline
splitlines ()with the default keepends (false). And we print the resulting lists of split lines.
As you can see from the output, since keepends was not installed, all split lines have no line boundaries or boundary characters. For line 2,
’’ is included in the word
’Askpython’ because it is not a boundary character (it is not in the table).
So the output is justified.
With matching line feeds included
If we specify keepends as
True , the split lines will now include matching line feeds.
Let’s modify our previous code (without keepends) by setting the keepends parameter to
True inside the
splitlines () string method. Take a close look at the result and try to notice the difference from the previous one.
# String initialization string1 = "Tim Charlie John Alan" string2 = "Welcome to AskPython! " string3 = "Keyboardu2028Monitoru2029x1cMousex0cCPUx85Motherboardx1eSpeakers UPS" #with keepends print (string1.splitlines (keepends = True)) print (string2.splitlines (keepends = True)) print (string3.splitlines (keepends = Truep)) :[’Tim’, ’Charlie’, ’John’, ’Alan’] [’ Welcome ’,’ ’,’ to ’ , ’AskPython!’] [’Keyboardu2028’,’ Monitoru2029’, ’x1c’,’ Mousex0c’, ’CPUx85’,’ Motherboardx1e’, ’Speakers’,’ UPS’]
As expected, for the same lines,
splitlines ()includes all boundary characters.