Using re.sub() or split() + join() method you can remove extra spaces between words in Python.
Python remove extra spaces between words Example
Simple example code.
import re string1 = "The fox jumped over the log." res = re.sub(' +', ' ', string1) print(res)
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.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.