Python String splitlines() Method
The splitlines()
method splits a string at line boundaries (such as \n
, \r
, or \n\r
) and returns a list of lines (as substrings) in the string.
Syntax
string.splitline(keepends)
Parameter
keepends
(Optional): If True
, line breaks are included in the resulting list. Default is False
.
Return Value
Returns a list of lines (as substrings) in the list.
Examples
Without Keeping Line Breaks
text = "Python\nis\nawesome"
lines = text.splitlines()
print(lines) # Output: ['Python', 'is', 'awesome']
Keeping Line Breaks
If you want to keep line breaks in the resulting list, you can set the keepends
parameter to True
.
text = "Python\nis\nawesome"
lines = text.splitlines(True)
print(lines) # Output: ['Python\n', 'is\n', 'awesome']
Multi-Line String
text = """Python
is
awesome"""
lines = text.splitlines()
print(lines) # Output: ['Python', 'is', 'awesome']
Line Boundaries
The splitlines()
method splits at the following line boundaries:
Escape Sequence | Name |
\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 |