Remove multiple spaces from string Python | Example code

You can remove more than 1 space (Unwanted space) between intermediate words in strings using re.sub() or split() + join() method.

Example remove multiple spaces from string Python

Simple example code.

Using re.sub()

Using the regex will unwanted space between the words to be just a single space using the appropriate regex string.

You have to import the re module.

import re

string1 = "The   fox jumped   over    the log."

res = re.sub(' +', ' ', string1)

print(res)

Output:

Remove multiple spaces from string Python

Using split() and join()

Another method to remove multiple spaces is the split and join function. First, convert the string into a list of words and then join with a single space using the join function.

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.