Last Updated : 02 Jan, 2025
In Python, the splitlines() method is used to break a string into a list of lines based on line breaks. This is helpful when we want to split a long string containing multiple lines into separate lines. The simplest way to use splitlines() is by calling it directly on a string. It will return a list of lines split by the newline characters.
Python
s = "Geeks\nfor\nGeeks"
# Splits the string at each newline
lines = s.splitlines()
print(lines)
['Geeks', 'for', 'Geeks']Syntax of splitlines() Method
Parametersstring.splitlines(keepends=False)
keepends (optional)
If we want to preserve the newline characters in the result, we can pass True as an argument to the keepends parameter. This keeps the newline characters (\n) in the list elements.
Python
s = "Geeks\nfor\nGeeks"
lines = s.splitlines(keepends=True)
print(lines)
['Geeks\n', 'for\n', 'Geeks']splitlines() with Empty Lines
splitlines() also handles empty lines. By default, it will return an empty string for lines that are completely blank.
Python
s = "Geeks\nfor\nGeeks"
lines = s.splitlines()
print(lines)
['Geeks', 'for', 'Geeks']
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4