Using re.sub() or split() + join() method to remove extra spaces between words in Python.
Python remove extra spaces between words Example
Simple example code.
Using re.sub()
Regular expressions need to import the re module. It will replace any number of spaces with a single space:
import re
string1 = "The fox jumped over the log."
res = re.sub(' +', ' ', string1)
print(res)
Output:
Using split() and join()
Without any arguments, a.split() will automatically split on whitespace and discard duplicates, the ” “.join() joins the resulting list into one string.
string1 = "The fox jumped over the log."
res = " ".join(string1.split())
print(res)
Output: The fox jumped over the log.
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.