How to replace multiple spaces with a single space in Python [3 Methods]

Have you ever come across a string in Python that has unnecessary spacing between the words or characters? If so then you are at the right place to find the solutions to your problem.

In this Python tutorial, I will describe the different methods to replace multiple spaces with a single space in Python.

In Python, replacing multiple spaces from a string means excluding all the extra whitespaces so that it only remains with a single space between each word in the string.

Learn different methods to replace multiple spaces with a single space in Python, such as:

  • Using regular expression (re)
  • Using the split() and join() method
  • Using for loop

Replace multiple spaces with a single space in Python using regular expression

Python has a built-in package called re (Regular Expressions), which can be used to work with Patterns.

You can use regular expressions to match consecutive space characters in the string and replace them with a single space in Python.

This is the complete source code of Python to replace multiple spaces with a single space using regular expression.

import re
Thought = "  Keep  Up The Good  Work"
print("String with multiple spaces:")
print(Thought)
print("String after removing multiple spaces:")
print(re.sub(' +', ' ', Thought))

The regular expression ‘ +’ matches one or more space characters. The re.sub() function in Python replaces all occurrences of this pattern with a single space.

print(re.sub(' +', ' ', Thought))

Output:

String with multiple spaces:
  Keep  Up The Good  Work
String after removing multiple spaces:
 Keep Up The Good Work

The screenshot below shows the output of the Python program to replace multiple spaces with a single space using regular expression.

Replace multiple spaces with a single space in Python

How to replace multiple spaces with a single space in Python using split() and join() method

To replace multiple spaces with one space in a Python string with join() and split(), you can first split the string using the space as the separator character.

READ:  Python List count() method [With Examples]

Then, you can take the resulting list of strings and use the string join() method to create the final string by specifying only one space as the separator.

This is complete Python code to replace multiple spaces with a single space using split() and join() methods.

input_text = "You  are capable  of amazing  things  "

words = input_text.split()
output_text = ' '.join(words)

print(output_text) 

Output:

You are capable of amazing things

Refer to the image below to see the output of the Python program to replace multiple spaces with a single space in Python using the split() and join() methods.

How to replace multiple spaces with a single space in Python

Python program to replace multiple spaces with a single space using a for loop

This is another approach to replace multiple spaces with a single space using a for loop by iterating through each character in the string and building a new string while skipping consecutive spaces.

Here is the full Python source code to replace multiple spaces with a single space using a for loop.

def replace_multiple_whitespaces(input_thought):
    result = ''
    is_space = False

    for char in input_thought:
        if char == ' ':
            if not is_space:
                result += char
            is_space = True
        else:
            result += char
            is_space = False
    return result

print(replace_multiple_whitespaces("The  Pain You Feel  Today The Strength  You Feel  Tomorrow  "))

Ultimately, it returns the modified string where consecutive whitespaces are replaced by a single whitespace in Python.

Output:

The Pain You Feel Today The Strength You Feel Tomorrow 

Refer to the screenshot below, and it will display the output of the Python program to replace multiple spaces with a single space using a for loop.

Replace multiple spaces with a single space in Python using for loop

Conclusion

I hope the information provided above is helpful. Here, I have explained three different methods to remove multiple spaces with a single space in Python, each offering unique advantages for different situations.

READ:  Python program for birthday wishes

Regular expressions offer a powerful way to handle complex pattern matching and replacement tasks in a single line in Python. The split() and join() methods in Python allow for the quick replacement of multiple spaces with a single space, and the for loop provides a more manual and step-by-step process in Python.

You may also like to read: