Sling Academy
Home/Python/Python: 3 ways to remove empty lines from a string

Python: 3 ways to remove empty lines from a string

Last updated: May 20, 2023

A multiple-line string might contain one or many empty lines. Empty lines refer to lines in a text or string that contain no visible content or characters. They are lines that appear blank or have only whitespace characters, such as spaces, tabs, or line breaks:

This is line 1.
    
This is line 3.

    This is line 5.

This concise, code-focused article will walk you through several examples that demonstrate how one can eliminate empty lines from a given string in Python in order to make the resulting string more compact and meaningful.

Using a List Comprehension

The idea here is to split the input string into lines, iterate over each line using a list comprehension, and select only the non-empty lines. Finally, join these lines back together to form a single string.

input_string = """
Welcome to Sling Academy

This is a multi-line string.
It contains empty lines.


There are some empty lines above this.
And another one below this.

Thank you!
"""

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)

print(remove_empty_lines(input_string))

Output:

Welcome to Sling Academy
This is a multi-line string.
It contains empty lines.
There are some empty lines above this.
And another one below this.
Thank you!

The remove_mepty_lines function in the code snippet above can also be rewritten like this (it’s a little bit longer but easier to debug):

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

Using the filter() Function

In this approach, the filter() function is used along with a lambda function to filter out the empty lines. The lambda function checks if the line, after stripping the leading and trailing whitespace, is not an empty string.

Example:

input_string = """

He thrusts his fists

against the posts
and still insists he sees the ghosts

I am a fish
"""

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

print(remove_empty_lines(input_string))

Output:

He thrusts his fists
against the posts
and still insists he sees the ghosts
I am a fish

Using Regular Expressions

This approach employs regular expressions (re module) to remove empty lines. It replaces multiple consecutive newline characters with a single newline character.

Example:

import re

input_string = """
One Two Three Four

Five Six Seven Eight

Nine Ten Eleven Twelve


"""

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

print(remove_empty_lines(input_string))

Output:

One Two Three Four
Five Six Seven Eight
Nine Ten Eleven Twelve

That’s it. Happy coding & have a nice day!

Next Article: Python: 3 Ways to Validate an Email Address

Previous Article: Python: How to unescape HTML entities in a string

Series: Working with Strings in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots