Python String splitlines() Method
Last Updated :
19 Aug, 2021
Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional).
Syntax:
string.splitlines([keepends])
Parameters:
keepends (optional): When set to True line breaks are included in the resulting list. This can be a number, specifying the position of line break or, can be any Unicode characters, like “\n”, “\r”, “\r\n”, etc as boundaries for strings.
Return Value:
Returns a list of the lines in the string, breaking at line boundaries.
splitlines() splits on the following line boundaries:
Representation
|
Description
|
\n |
Line Feed |
\r |
Carriage Return |
\r\n |
Carriage Return + Line Feed |
\x1c |
File Separator |
\x1d |
Group Separator |
\x1e |
Record Separator |
\x85 |
Next Line (C1 Control Code) |
\v or \x0b |
Line Tabulation |
\f or \x0c |
Form Feed |
\u2028 |
Line Separator |
\u2029 |
Paragraph Separator |
Example 1
Python3
string = "Welcome everyone to\rthe world of Geeks\nGeeksforGeeks"
print (string.splitlines( ))
print (string.splitlines( 0 ))
print (string.splitlines( True ))
|
Output:
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to\r', 'the world of Geeks\n', 'GeeksforGeeks']
Example 2
Python3
string = "Cat\nBat\nSat\nMat\nXat\nEat"
print (string.splitlines( ))
print ( 'India\nJapan\nUSA\nUK\nCanada\n' .splitlines())
|
Output:
['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat']
['India', 'Japan', 'USA', 'UK', 'Canada']
Example 3: Practical Application
In this code, we will understand how to use the concept of splitlines() to calculate the length of each word in a string.
Python3
def Cal_len(string):
li = string.splitlines()
print (li)
l = [ len (element) for element in li]
return l
string = "Welcome\rto\rGeeksforGeeks"
print (Cal_len(string))
|
Output:
['Welcome', 'to', 'GeeksforGeeks']
[7, 2, 13]
Share your thoughts in the comments
Please Login to comment...