Python remove extra spaces between words | Example code

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.

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:

Python remove extra spaces between words

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)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.