The splitlines()
method in Python is used to split a string into a list of lines. It separates the string at line breaks and returns a list containing each line as a separate element.
Parameter Values
This function does not accept any parameters.Return Values
The splitlines()
method returns a list of strings.
How to Use splitlines()
in Python
Example 1:
The splitlines()
method splits a string into a list of lines. It uses line break characters such as '\n', '\r', or '\r\n' as the delimiter.
text = 'Hello\nWorld\nPython'
lines = text.splitlines()
print(lines)
Example 2:
By default, the splitlines()
method keeps the line break characters at the end of each line. You can remove them by setting the keepends
parameter to False.
text = 'Hello\nWorld\nPython'
lines = text.splitlines(keepends=False)
print(lines)
Example 3:
The splitlines()
method can also be used to split multiline strings read from a file into individual lines.
with open('file.txt', 'r') as file:
content = file.read()
lines = content.splitlines()
print(lines)