Logo

Programming-Idioms

  • Python
  • Obj-C
  • Lua

Idiom #219 Replace multiple spaces with single space

Create the string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.

local t = s:gsub("%s+", " ")

string.gsub(s, "%s+", " ") can be used instead of s:gsub("%s+", " ")
from re import split
t = ' '.join(split(' {2,}', s))
t: str = " ".join(s.split())

Splits s into a list based on whitespace, then joins them together again
import re
t = re.sub(' +', ' ', s)

Only replaces spaces.
from re import split
t = ' '.join(split(r'\s{2,}', s))
(def t (clojure.string/replace s #"\s+" " "))

New implementation...