Python String splitlines() method (original) (raw)
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)
`
Output
['Geeks', 'for', 'Geeks']
Table of Content
- Syntax of splitlines() Method
- splitlines() with keepends=True
- Processing Log Files
- splitlines() with Empty Lines
Syntax of splitlines() Method
string.splitlines(keepends=False)
**Parameters
keepends (optional)
- **Type: bool
- **Default Value: False
**Return Type:
- If **keepends=True, each line in the list will include the line break characters.
- If keepends=False (default), the line breaks are removed from the lines in the returned list.
splitlines() with keepends=True
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)
`
Output
['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)
`
Output
['Geeks', 'for', 'Geeks']