PythonString methods
str. splitlines()
Splits a string into a list of lines.
- Returns
- A list of lines.
- Changes the original
- No
Example
#Python
text = "HTML\nCSS\r\nPython\n"
print(text.splitlines())
print(text.split("\n"))Resultsaved result, you can check it
['HTML', 'CSS', 'Python']
['HTML', 'CSS\r', 'Python', '']
Definition and usage
#The splitlines() method splits text into lines, recognizing different line-ending characters: \n, \r\n, and others. The line-ending characters do not end up in the result.
Unlike split("\n"), it does not create an empty element at the end when the text ends with a newline character, and it correctly handles files from Windows.
The keepends=True argument keeps the line-ending characters on every element.
Syntax
#Syntax
string.splitlines(keepends=False)Parameters
#keepends
bool, default False
Whether to keep the line-ending characters.
Good practices
#- Choose
splitlines()instead ofsplit("\n")for splitting text into lines. - When reading a file, you can iterate directly over the file object, line by line.
Related entries
#Spotted a mistake or missing an example? Write to us.