How to Split Lines and Strip Blank Lines in Python

Split a multiline string into non-empty lines and strip surrounding whitespace using a list comprehension.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

14 lines
Python 3.9+
import sys

def split_and_strip(text):
    """Split text into non-blank lines, stripping whitespace."""
    return [line.strip() for line in text.splitlines() if line.strip()]

if __name__ == "__main__":
    sample_text = """  First line   
    
    Second line	
      
    Third line  """
    result = split_and_strip(sample_text)
    print(result)

Output

stdout
['First line', 'Second line', 'Third line']

How it works

The splitlines() method splits the text at line breaks and removes the line-ending characters. The list comprehension iterates over each line, and line.strip() removes leading and trailing whitespace. The if line.strip() condition filters out lines that are empty or contain only whitespace by checking if the stripped line is truthy. This approach is efficient and concise, handling multiple types of line endings like \n, \r\n, and \r.

Common mistakes

  • Using `split('\n')` instead of `splitlines()` misses lines with `\r\n` and leaves empty strings when there are consecutive newlines.
  • Forgetting to strip lines before filtering, so lines with only spaces are considered non-blank.
  • Modifying the original text instead of creating a new list, leading to unintended side effects.

Variations

  1. Use a generator expression and `filter` to create an iterator: `filter(None, (line.strip() for line in text.splitlines()))`.
  2. Use `re.findall(r'[^\n].*', text)` with a regex to extract non-empty lines, though it's less readable.

Real-world use cases

  • Cleaning log files by extracting meaningful non-empty lines and removing whitespace before analysis.
  • Parsing configuration files or CSV-like text where blank lines should be ignored.
  • Processing user input from multi-line textareas, filtering out empty submissions.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.