Sling Academy
Home/Python/Python: 2 ways to remove multiple consecutive whitespaces

Python: 2 ways to remove multiple consecutive whitespaces

Last updated: June 01, 2023

Multiple consecutive spaces in a string are spaces that occur more than once in a row, one follows another in a continuous series. They can make the string look uneven or messy.

For instance, let’s have a glance at the string below:

text = "This is    a   string with  consecutive   white spaces."

As you can see, there are multiple consecutive spaces between some of the words. To make the string look better, we can remove them and keep only one space between each word. There are different ways to do so. Let’s explore them one by one in this concise, practical article.

Using regular expressions

This approaches use the re.sub() function from the re module to replace multiple consecutive spaces with a single space.

Example:

import re

text = "This is    a   string with  consecutive   white spaces."
text = re.sub("\s+", " ", text)
print(text)

Output:

This is a string with consecutive white spaces.

This method is elegant and efficient. You can get the job done with only a single line of code.

Using the string split() and join() methods

An alternative solution is to use the split() and join() methods to split the string by whitespace characters and join them back with a single space.

Example:

text = "Welcome   to Sling    Academy.     Happy      coding!"
text = " ".join(text.split())
print(text)

Output:

Welcome to Sling Academy. Happy coding!

This technique is concise, too. All unwanted multiple spaces were replaced with single spaces.

Next Article: 2 ways to get the size of a string in Python (in bytes)

Previous Article: Python: How to Convert a String to Character Codes

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