Python Methods to Remove Empty Lines from Multi-line Input Text

Answered using ChatGPT 4o by ChatGPT4o

Question:

python: remove empty lines of a multi-line input text

Answer:

To remove empty lines from a multi-line input text in Python, you can use several methods. Here are a few common approaches:

Method 1: Using List Comprehension

def remove_empty_lines(text):
    lines = text.split('\n')
    non_empty_lines = [line for line in lines if line.strip() != '']
    return '\n'.join(non_empty_lines)

input_text = """This is a line.

This is another line.

And another one.
"""

output_text = remove_empty_lines(input_text)
print(output_text)

Method 2: Using filter and str.strip

def remove_empty_lines(text):
    lines = text.split('\n')
    non_empty_lines = filter(lambda x: x.strip() != '', lines)
    return '\n'.join(non_empty_lines)

input_text = """This is a line.

This is another line.

And another one.
"""

output_text = remove_empty_lines(input_text)
print(output_text)

Method 3: Using Regular Expressions

import re

def remove_empty_lines(text):
    return re.sub(r'\n\s*\n', '\n', text.strip())

input_text = """This is a line.

This is another line.

And another one.
"""

output_text = remove_empty_lines(input_text)
print(output_text)

Method 4: Using str.splitlines and str.join

def remove_empty_lines(text):
    lines = text.splitlines()
    non_empty_lines = [line for line in lines if line.strip()]
    return '\n'.join(non_empty_lines)

input_text = """This is a line.

This is another line.

And another one.
"""

output_text = remove_empty_lines(input_text)
print(output_text)

All these methods will produce the same output:

This is a line.
This is another line.
And another one.

Choose the method that you find most readable and suitable for your