Python Splitlines
There are several different functions available in Python for performing various functionalities upon the strings. One of Python’s useful built-in string methods is the “splitlines()” method. This method splits a target string into a list of lines based on line breaks such as “\n” or “\r”.
This post will present a complete guide on the Python “splitlines()” method by covering the following content:
What is the “splitlines()” Method in Python?
In Python, the “splitlines()” method is utilized to retrieve the list by splitting a string or line at line boundaries. The line breaks are used to split the lines.
Syntax
Parameter Value
In the above syntax, the “keepends” is an optional parameter that specifies whether the line breaks should be included. If “True”, line breaks are included, and if “False”, they are not included.
Return Value
The “string.splitlines()” method retrieves the list object, including all the lines.
Example 1: Split the String by Including the Line Breaks
The below example code is utilized to split the string:
print('Line Break Included:', str1.splitlines(True))
In the above code, the “string.splitlines()” method takes the “True” value as its parameter and splits the string into the list by including the line break character.
Output
Based on the above output, the string has been split into a list keeping the line breaks.
Example 2: Split the String Without Including the Line Breaks
Let’s overview the below example code for splitting the string without line breaks:
print('Line Break Not Included:', str1.splitlines(False))
In the above code lines, the “string.splitlines()” method takes the “False” value as a parameter and retrieves the list by splitting the string. The retrieved list does not include the line break character.
Output
Based on the above output, the string has been split into lists without line breaks.
Example 3: Applying the “splitlines()” Method Upon the Multiline String
The below example code is used to split the string into a Python list:
and Welcome
to Python Guide'''
print(str1.splitlines())
In the above code, the “str1.splitlines()” method is used to split the multiline string named “str1” into the list.
Output
The multiline string has been split into the list appropriately.
Conclusion
The “string.splitlines()” method in Python splits or breaks the given string at line break(s) and retrieves the list object. This method takes the Boolean value “True” and “False” to keep or omit the line break character while splitting the string. This post presented a thorough guide on splitting the lines using the “string.splitlines()” method with several examples.
Source: linuxhint.com