If you want to remove leading and ending whitespace, use str.strip():
Copy>>> " hello apple ".strip()
'hello apple'
If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace):
Copy>>> " hello apple ".replace(" ", "")
'helloapple'
If you want to remove all whitespace and then leave a single space character between words, use str.split() followed by str.join():
Copy>>> " ".join(" hello apple ".split())
'hello apple'
If you want to remove all whitespace then change the above leading " " to "":
Copy>>> "".join(" hello apple ".split())
'helloapple'
Answer from Cédric Julien on Stack OverflowIf you want to remove leading and ending whitespace, use str.strip():
Copy>>> " hello apple ".strip()
'hello apple'
If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace):
Copy>>> " hello apple ".replace(" ", "")
'helloapple'
If you want to remove all whitespace and then leave a single space character between words, use str.split() followed by str.join():
Copy>>> " ".join(" hello apple ".split())
'hello apple'
If you want to remove all whitespace then change the above leading " " to "":
Copy>>> "".join(" hello apple ".split())
'helloapple'
To remove only spaces use str.replace:
Copysentence = sentence.replace(' ', '')
To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:
Copysentence = ''.join(sentence.split())
or a regular expression:
Copyimport re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
If you want to only remove whitespace from the beginning and end you can use strip:
Copysentence = sentence.strip()
You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.
methods to remove spaces from text
Strip Command doesn't remove white space of a string stored in a variable
How to Remove Spaces From a String in Python (Complete 2026 Guide)
I must be an idiot or something. Why can't I strip the comma's out of a string?
Videos
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))