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.
Python code
14 linesimport 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
['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
- Use a generator expression and `filter` to create an iterator: `filter(None, (line.strip() for line in text.splitlines()))`.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.