October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

Replace Multiple Spaces with a Single Space in Python

Use ' '.join(text.split()) to collapse whitespace and trim a Python string, or a targeted regex to change repeated ordinary spaces only.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To collapse runs of whitespace into one ordinary space in Python, use ' '.join(text.split()). It also removes whitespace from the beginning and end of the string. If you want to collapse only repeated literal spaces while preserving tabs and line breaks, use re.sub(r' {2,}', ' ', text).

Collapse whitespace and trim the string

Call split() without an argument to treat each run of whitespace as a separator, then join the resulting pieces with one ordinary space:

As an Amazon Associate I earn from qualifying purchases.

text = '  one   twotthree  '
cleaned = ' '.join(text.split())
print(cleaned)
# one two three

This built-in approach collapses whitespace runs and removes leading and trailing whitespace. The tab between two and three is treated as whitespace too. See Python’s string methods documentation for split() and join().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Change repeated spaces without changing tabs or newlines

If “spaces” means only the ordinary space character, use a regular expression that matches two or more spaces:

import re

text = 'one   twotthree'
cleaned = re.sub(r' {2,}', ' ', text)
print(cleaned)
# one twotthree

The pattern {2,} matches repeated literal spaces, not tabs or line breaks, so those characters remain unchanged. re.sub() replaces matches with the supplied replacement string; Python documents this behavior in its Regular Expression HOWTO.

Choose the right method for the input

Goal Expression Effect
Collapse whitespace runs and trim the edges ' '.join(text.split()) Replaces each whitespace-separated boundary with one ordinary space and drops leading or trailing whitespace.
Collapse repeated literal spaces only re.sub(r' {2,}', ' ', text) Changes runs of ordinary spaces; leaves tabs and line breaks alone.
Collapse regex-recognized whitespace re.sub(r's+', ' ', text) Replaces runs matched by s; for Unicode string patterns, Python’s regex documentation defines this in relation to str.isspace().
Replace a known exact substring text.replace(old, new) Replaces occurrences of that substring; it does not match a pattern for arbitrary runs.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Avoid common string-method pitfalls

Do not pass a space to split when you want grouped separators

text.split(' ') uses a literal space as its separator. Consecutive separators can produce empty strings rather than being grouped as one whitespace run. For general whitespace normalization, leave the argument out: text.split().

Do not expect split and join to preserve edge whitespace

' '.join(text.split()) intentionally removes whitespace at the start and end. If only internal literal spaces should change and edge characters must remain untouched, use the literal-space regular expression instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A single replace call is not a general run-collapsing operation

text.replace(' ', ' ') replaces occurrences of the exact two-space substring. It is not a pattern matcher for arbitrary whitespace, so it is not the clearest general solution for runs of different lengths. Python describes str.replace() as returning a copy with occurrences of the specified substring replaced in its Built-in Types reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.