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.