python

Convert multiple spaces of a string to single space in python [with and without regex]

The easiest way to replace multiple spaces from a string with a single space is by using. We are also describing methods apart from regex.

#Using regex
import re

mystr = 'This    string  contains multiple     spaces'
result = re.sub(' +', ' ', mystr)
print(result)

# Without using regex
result2 = " ".join(mystr.split())
print(result2)
Output
This string contains multiple spaces

In the above code snippet, we are importing the python regex module re. The regex function re.sub() can be used to remove multiple spaces between words of a string with single space.

More methods for the same can be found below.

space_str = 'Words   that   contains   multiple    spaces'
res_str = " ".join(space_str.split())
print(res_str)
# -> Words that contains multiple spaces
The above code does not use any python regex module and it will remove more than one space and add a single space between words. We are using the python .join() method for that.
Was this helpful?