Search code snippets, questions, articles...

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)

# Without using regex
result2 = " ".join(mystr.split())
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
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())
# -> 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?