>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'
Answer from Josh Lee on Stack Overflow>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'
foo is your string:
" ".join(foo.split())
Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)" (thanks to hhsaffar, see comments). I.e., "this is \t a test\n" will effectively end up as "this is a test".
methods to remove spaces from text
How to remove extra space
How to Remove Spaces From a String in Python (Complete 2026 Guide)
How to remove whitespaces from a string in Python?
Hi everyone, I recently took the Fullstack Python Developer course and am now taking my first steps on this path.
Can you tell me what other methods of removing spaces from text you know and in which case, each of them is better to use?
So far I know 4 of them:
-
replace method -> text_wo_spaces = text.replace(" ","")
-
join and split methods -> text_wo_spaces = ' '.join(text.split())
-
list generator + join -> text_wo_spaces = ' '.join([char for char in text if char != ' '])
-
filter + join methods -> text_wo_spaces = ' '.join(filter(lambda char : != ' ', text))