Content · Programming · Python

Python str.splitlines Method: Usage and Examples

str.splitlines(keepends=False) separates text into lines at common newline boundaries. By default it removes line endings; keepends=True preserves them in the returned list. Learn with a clear example and common.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.splitlines Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.splitlines(keepends=False) separates text into lines at common newline boundaries. By default it removes line endings; keepends=True preserves them in the returned list.

When You Would Use This


Process a short multiline note without keeping newline characters.

Step-by-Step Example


note_text = "First task\nSecond task\n"
print(note_text.splitlines())
print(note_text.splitlines(keepends=True))

How the Example Works


The default result has two text lines without newline characters. With keepends=True, each returned line retains its line terminator. The trailing newline does not add a final empty element.

Example Output


['First task', 'Second task']
['First task\n', 'Second task\n']

Try It Yourself


Compare `.split(" ") and .splitlines()` on a string ending with a newline.

Common Beginner Mistakes


  • Expecting a trailing newline to create a separate empty line.
  • Forgetting to use keepends=True when reconstructing exact text.
  • Assuming all line endings consist only of ` `.

Key Takeaways


  • str.splitlines(keepends=False) separates text into lines at common newline boundaries.
  • The default result has two text lines without newline characters.
  • Avoid this mistake: Expecting a trailing newline to create a separate empty line.
Share this resourceSend this page to someone who may find it useful.