python: remove empty lines of a multi-line input text
To remove empty lines from a multi-line input text in Python, you can use several methods. Here are a few common approaches:
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)
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)
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)
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