Python String splitlines() Method
The splitlines() method in Python is used to split a string into a list of lines. It's especially useful when you're working with multiline strings, files, or text blocks where line breaks matter.
Syntax
string.splitlines(keepends=False)
Parameters:
keepends(optional) – IfTrue, line break characters (\n,\r,\r\n) are included in the output. Default isFalse.
Returns:
- A
listof lines in the string.
Example 1: Basic Usage
text = "Hello\nWorld\nPython"
lines = text.splitlines()
print(lines)
['Hello', 'World', 'Python']
Example 2: Keeping Line Breaks
text = "Hello\nWorld\nPython"
lines = text.splitlines(keepends=True)
print(lines)
['Hello\n', 'World\n', 'Python']
Use Case: Reading File Content
When reading file content into a single string, you can use splitlines() to process each line easily.
with open("file.txt", "r") as file:
content = file.read()
lines = content.splitlines()
for line in lines:
print(line)
Line Breaks Handled
splitlines() automatically handles:
\n– Unix/Linux line break\r\n– Windows line break\r– Old Mac line break
Common Mistakes
- Using
split('\n')instead ofsplitlines()will miss other newline types like\rand\r\n. - Forgetting to set
keepends=Truewhen line endings are important (e.g., in formatting).
Interview Tip
Use splitlines() in coding questions where you need to parse multi-line input efficiently. It’s cleaner than splitting manually with split('\n').
Summary
splitlines()splits a string into lines based on all common line break characters.- Returns a list of strings (lines).
- Use
keepends=Trueto retain line break characters.
Practice Problem
Write a program that reads a multi-line input from the user and prints each line with its line number.
text = """Python\nIs\nAwesome"""
for i, line in enumerate(text.splitlines(), 1):
print(f"Line {i}: {line}")
Comments
Loading comments...