#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)
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
0 Comments