Replace Multiple Spaces with a Single Space in Python

By James L.

When working with strings, you might encounter unwanted extra spaces between them, usually because of accidental key presses or how you naturally type.

This guide will help you learn different ways to eliminate and replace these extra spaces with just one. We will explore the following approaches:

  • Using split() and join()
  • Using regular expressions
  • Using a for loop

# Using split() and join()

You can replace multiple spaces with a single space in Python using the split() and join() methods.

Here’s an example:

my_str = "I    love Python   programming"

# Split the string into a list of words using space as the delimiter
words = my_str.split()

# Join the words back together with a single space as the delimiter
output_str = ' '.join(words)

print(output_str)  # Output: I love Python programming

In this example, the split() method without any arguments splits the string based on any whitespace (such as newlines, tabs, and spaces) and returns a list of words. Then, the join() method joins these words back together into a string with a single space between each word. This way, any consecutive spaces in the original string are replaced with a single space.

# Using regular expressions

You can use the re module in Python to replace multiple spaces with a single space.

Here’s an example:

import re

my_str = "I    love Python   programming"

# Define a regex pattern that matches one or more space characters
pattern = r' +'

# Use the re.sub() function to replace matches of the pattern with a single space
new_str = re.sub(pattern, ' ', my_str)

print(new_str)  # Output: I love Python programming

In this example, the regular expression r' +' matches one or more space characters. The re.sub() function replaces all occurrences of this pattern with a single space.

If you want to handle other whitespace characters such as newline and tabs, you can do that by adjusting the above code as follows: 

import re

my_str = "I    love Python   programming"

# Define a regex pattern that matches one or more whitespace characters
pattern = r'\s+'

# Use the re.sub() function to replace matches of the pattern with a single space
new_str = re.sub(pattern, ' ', my_str)

print(new_str)  # Output: I love Python programming

In this example, the regular expression r'\s+' matches one or more whitespace characters (including spaces, tabs, and newlines). The re.sub() function replaces all occurrences of this pattern with a single space.

Handling leading and trailing whitespace characters

If the string contains leading and trailing whitespace characters, the resulting string will retain these leading and trailing whitespace characters even after replacing multiple whitespace characters with a single space.

You can use the strip() method to remove these leading and trailing whitespaces and then use a regular expression to replace multiple whitespace characters with a single space.

Here’s an example:

import re

my_str = "   I    love Python   programming  "

# Use strip() to remove leading and trailing whitespaces
my_str = my_str.strip()

# Define a regex pattern that matches one or more whitespace characters
pattern = r' +'

# Use the re.sub() function to replace matches of the pattern with a single space
new_str = re.sub(pattern, ' ', my_str)

print(new_str)  # Output: I love Python programming

# Using a for loop

You can 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’s an example:

def replace_multiple_spaces(input_string):
    # Initialize an empty string to store the modified result
    result = ''

    # Flag to track whether the previous character was a space
    is_space = False

    # Iterate through each character in the input string
    for char in input_string:
        # Check if the current character is a space
        if char == ' ':
            # Check if the previous character was not a space
            if not is_space:
                # Add the space to the result if it's the first consecutive space
                result += char
            # Set the flat to True to indicate the presence of a space
            is_space = True
        else:
            # Add non-space characters directly to the result
            result += char
            # Reset the flat to False since the current character is not a space
            is_space = False
    return result


print(replace_multiple_spaces("I  love   Python     Programming"))

In this example, the is_space flag is used to determine whether the current character is a space and whether the previous character was also a space. If consecutive spaces are encountered, only one space is added to the result to replace them.

Conclusion

In conclusion, we have explored three different methods to remove multiple spaces with a single space in Python, each offering unique advantages for different situations.

The split() and join() methods provide a concise and elegant solution, allowing for quick replacement of multiple spaces with a single space.

Regular expressions offer a compact and powerful way to handle complex pattern matching and replacement tasks in a single line, making them ideal for handling diverse whitespace issues.

If you need to handle different types of whitespace characters (such as spaces, newlines, and tabs), use the \s+ in the regular expression.

The for loop provides a more manual and step-by-step process for those who prefer explicit control over their code.

Also, to remove the leading and trailing whitespaces, use the strip() method before applying any of these methods.

For large strings or frequent operations, the split() and join() methods or the for loop might be more efficient.

happy coding ***