To replace multiple spaces with one space using Python, the easiest way is to use the Python sub() function from the re module.

import re

string_multiple_spaces = "This   is    a string      with    some   multiple    spaces."

string_single_space = re.sub('s+',' ',string_multiple_spaces)

print(string_single_space)

#Output:
This is a string with some multiple spaces.

Another method to replace multiple spaces with one space is combining the use of split() and join.

string_multiple_spaces = "This   is    a string      with    some   multiple    spaces."

string_single_space = " ".join(string_multiple_spaces.split())

print(string_single_space)

#Output:
This is a string with some multiple spaces.

When using string variables in Python, we can easily perform string manipulation to change the value of the string variables.

One such manipulation is to remove characters from a string variable. Multiple spaces between words in a string of text can make sentences and text unreadable.

We can easily replace multiple spaces with single spaces in a string in Python.

The easiest way to get rid of multiple spaces in a string is with a regular expression search using the Python sub() function from the re module.

We can easily define a regular expression which will search for any number of spaces, and then using the sub() function, we will replace the multiple spaces with one space.

Below are some examples of how you can replace multiple spaces with one space in strings using Python with the sub() function.

import re

string_multiple_spaces = "This   is    a string      with    some   multiple    spaces."

string_single_space = re.sub('s+',' ',string_multiple_spaces)

print(string_single_space)

#Output:
This is a string with some multiple spaces.

Using join() and split() to Replace Multiple Spaces with One Space in Python

Another way you can replace multiple spaces with one space in Python is by combing the join() and split() functions.

By default, the split() function splits with space as delimiter. When there are multiple spaces, those extra spaces are ignored.

Therefore, we can use the split() function to get a list of words in the string, and then use the join() method to join the words together with a single space.

Below is an example of how to use the join() and split() functions in Python to replace multiple spaces with single spaces.

string_multiple_spaces = "This   is    a string      with    some   multiple    spaces."

string_single_space = " ".join(string_multiple_spaces.split())

print(string_single_space)

#Output:
This is a string with some multiple spaces.

Hopefully this article has been useful for you to learn how to replace multiple spaces with one space using Python.

Categorized in:

Python,

Last Update: March 18, 2024