The method splitlines() returns a list with all the lines in string, optionally including the line breaks (if num is supplied and is true)
The syntax of the method is: str.splitlines( num = string.count('\n'))
Key Points :
• When the string is interrupted, various lines are combined into a list returned by this function. We may then assume that it returns a split lines array.
• The numerous line break forms are \n(newline character), \r(carriage return), \r\n(carriage back+new line).
We’ll be covering the following topics in this tutorial:
splitlines() Parameters
Splitlines() takes up to 1 parameter.
• An optional parameter that may take one of two values: true or false.
The line breaks are included in the resulting list when this parameter is set to True. It may be numerical, which defines a line break position or some Unicode characters, such as \n, \r, \r\n, etc., which serve as a string boundary.
Return Value from splitlines()
This method returns a list consisting of the main string lines which are broken down on the basis of the boundaries characters in the main string.
Below is the python program to demonstrate the splitlines() function:
str = "Q1 Delhi\nQ2 Mumbai\n\nQ3 Pune"; print (str.splitlines( )) print (str.splitlines( 0 )) print (str.splitlines( 5 ))
When we run above the program, the outcome is as follows:
[‘Q1 Delhi’, ‘Q2 Mumbai’, ”, ‘Q3 Pune’]
[‘Q1 Delhi’, ‘Q2 Mumbai’, ”, ‘Q3 Pune’]
[‘Q1 Delhi\n’, ‘Q2 Mumbai\n’, ‘\n’, ‘Q3 Pune’]
Supported Splitlines() method line boundary characters:
The splitlines() method split lines on the following line boundary characters:
Representation | Description |
\n | Line Feed |
\r | Carriage Return |
\r\n | Carriage Return + Line Feed |
\v or \x0b | Line Tabulation |
\f or \x0c | Form Feed |
\x1c | File Separator |
\x1d | Group Separator |
\x1e | Record Separator |
\x85 | Next Line (C1 Control Code) |
\u2028 | Line Separator |
\u2029 | Paragraph Separator |
Below are several other functions that we can use to work with string in Python 3