If you want to remove leading and ending whitespace, use str.strip():

Use with AI>>> "  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):

Use with AI>>> "  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():

Use with AI>>> " ".join("  hello  apple  ".split())
'hello apple'

If you want to remove all whitespace then change the above leading " " to "":

Use with AI>>> "".join("  hello  apple  ".split())
'helloapple'
Answer from Cédric Julien on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-remove-spaces-from-a-string
Remove spaces from a string in Python - GeeksforGeeks
If we only want to remove spaces from the beginning of the string, we can use lstrip().
Published: July 11, 2025
Discussions

How to Remove Spaces From a String in Python (Complete 2026 Guide)
This does not affect spaces inside or at the end of the string. ... Use rstrip() to remove whitespace from the right side. ... This removes whitespace only from the beginning and end. Q) How do I remove multiple consecutive spaces in Python? More on accuweb.cloud
🌐 accuweb.cloud
1
December 1, 2023
methods to remove spaces from text
You are missing a regex. And the best one is number 1. Because of readability. Plus numbers 2, 3 and 4 don't work. You are putting the space back. More on reddit.com
🌐 r/learnpython
16
6
December 20, 2023
python - How to strip all whitespace from string - Stack Overflow
I'm not sure what the current state ... in Python used to have not so great performance. For light usage my example would be fine, but for processing large strings performance could become an issue. 2022-12-03T23:52:47.173Z+00:00 ... Save this answer. ... Show activity on this post. ... Copyimport string def remove_whitespace(in_string: ... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I trim whitespace from a string? - Stack Overflow
How do I remove leading and trailing whitespace from a string in Python? " Hello world " --> "Hello world" " Hello world" --> "Hello world" "Hello More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How do .strip(), .lstrip(), and .rstrip() handle strings with mixed whitespace characters like tabs or newlines?

By default, these methods remove all types of whitespace, including spaces, tabs (\t), and newlines (\n). For example:

text = "\t\n  Python Programming  \n\t"
trimmed_text = text.strip()
print(trimmed_text)  # Output: "Python Programming"
🌐
datacamp.com
datacamp.com › home › tutorials › python › how to trim a string in python: three different methods
How to Trim a String in Python: Three Different Methods | DataCamp
Can I use .strip(), .lstrip(), or .rstrip() to remove numeric characters from a string?

Yes, you can specify numeric characters as the target for removal. For example:

text = "12345Python12345"
trimmed_text = text.strip('12345')
print(trimmed_text)  # Output: "Python"
🌐
datacamp.com
datacamp.com › home › tutorials › python › how to trim a string in python: three different methods
How to Trim a String in Python: Three Different Methods | DataCamp
What happens if I call .strip(), .lstrip(), or .rstrip() on an empty string?

If you call these methods on an empty string, they return an empty string without errors. For example:

text = ""
trimmed_text = text.strip()
print(trimmed_text)  # Output: ""
🌐
datacamp.com
datacamp.com › home › tutorials › python › how to trim a string in python: three different methods
How to Trim a String in Python: Three Different Methods | DataCamp
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-remove-spaces-from-string
Effective Ways to Remove Spaces from Strings in Python | DigitalOcean
July 11, 2025 - Master Python string manipulation by learning how to remove whitespace and manage spaces with techniques like strip(), replace(), and regex for cleaner data.
🌐
Mimo
mimo.org › tutorials › python › how-to-remove-spaces-from-a-string-in-python
How to Remove Spaces from a String in Python
If you want to delete regular space characters (" ") everywhere in the string, use .replace(" ", ""). ... This also removes normal spaces and can feel easier to read. ... What to look for: split(" ") only targets normal spaces. Tabs and newlines remain. If input can contain tabs, newlines, or mixed whitespace, use split() with no argument.
🌐
Python Morsels
pythonmorsels.com › remove-spaces
How to remove spaces in Python - Python Morsels
January 25, 2022 - We could use the string split and join methods, as before, but join on a space character instead of an empty string: >>> version = "\tpy 310\n" >>> normalized_spaces = " ".join(version.split()) >>> normalized_spaces 'py 310' Note that this normalizes all whitespace characters (so newlines and tabs will be converted as well) and it removes spaces from the ends of our string.
🌐
W3Schools
w3schools.com › python › ref_string_strip.asp
Python String strip() Method
The strip() method removes any leading, and trailing whitespaces. Leading means at the beginning of the string, trailing means at the end.
Find elsewhere
🌐
DataCamp
datacamp.com › home › tutorials › python › how to trim a string in python: three different methods
How to Trim a String in Python: Three Different Methods | DataCamp
February 16, 2025 - Python provides built-in methods to trim strings, making it straightforward to clean and preprocess textual data. These methods include · .strip(): Removes leading and trailing characters (whitespace by default).
🌐
Accuweb
accuweb.cloud › home › how to remove spaces from a string in python (complete 2026 guide)
How to Remove Spaces From a String in Python (Complete 2026 Guide)
December 1, 2023 - This does not affect spaces inside or at the end of the string. ... Use rstrip() to remove whitespace from the right side. ... This removes whitespace only from the beginning and end. Q) How do I remove multiple consecutive spaces in Python?
🌐
freeCodeCamp
freecodecamp.org › news › python-strip-how-to-trim-a-string-or-line
Python strip() – How to Trim a String or Line
January 12, 2022 - Use the .rstrip() method to remove whitespace and characters only from the end of a string. If you want to learn more about Python, check out freeCodeCamp's Python Certification. You'll start learning in an interacitve and beginner-friendly way.
🌐
DEV Community
dev.to › trinityyi › how-do-i-trim-whitespace-from-a-string-in-python-309o
How do I trim whitespace from a string in Python? - DEV Community
September 15, 2022 - Leading whitespace characters are the whitespace characters at the start of a string. To remove them, use the str.lstrip() method.
🌐
Sentry
sentry.io › sentry answers › python › remove whitespace from a string in python
Remove whitespace from a string in Python | Sentry
July 3, 2026 - str.strip() only removes whitespace from the ends of the string. We can remove all space characters from a string using str.replace() to replace them with empty strings:
🌐
FavTutor
favtutor.com › blogs › remove-space-from-string-python
Remove Spaces from String in Python | FavTutor
January 6, 2022 - Using this method, only the trailing spaces can be removed in a string. ... The string strip() method can be used to eliminate spaces from both the beginning and end of a string. Learn more about rstrip in python here.
🌐
Real Python
realpython.com › python-strip
How to Strip Characters From a Python String – Real Python
October 22, 2025 - If you don’t provide any arguments to the method, then .strip() removes all leading and trailing whitespace characters, leaving any whitespace within the string untouched: ... When you call .strip() on a string object, Python removes the leading and trailing spaces while keeping the spaces between words unchanged...
🌐
GeeksforGeeks
geeksforgeeks.org › python-remove-spaces-from-a-string
Remove spaces from a string in Python - GeeksforGeeks
Similarly, to remove spaces from the end of a string, we can use rstrip(). ... Explanation: s.rstrip() removes spaces from the right side of s only. ... In today’s digital world, data is the key to unlocking valuable insights, and much ...
Published: April 17, 2025
🌐
Reddit
reddit.com › r/learnpython › methods to remove spaces from text
r/learnpython on Reddit: methods to remove spaces from text
December 20, 2023 -

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:

  1. replace method -> text_wo_spaces = text.replace(" ","")

  2. join and split methods -> text_wo_spaces = ' '.join(text.split())

  3. list generator + join -> text_wo_spaces = ' '.join([char for char in text if char != ' '])

  4. filter + join methods -> text_wo_spaces = ' '.join(filter(lambda char : != ' ', text))

🌐
Codingem
codingem.com › home › how to remove spaces from string in python
How to Remove Spaces from String in Python - codingem.com
July 10, 2025 - To remove spaces from a string in Python, use the str.replace() method. For example "This is a test".replace(" ", "") returns Thisisatest.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-strip-trailing-whitespace-in-python
Trim a String in Python – How to Strip Trailing Whitespace
March 3, 2023 - To remove both leading and trailing whitespace from the phrase, call the strip() method on fave_phrase and store the result in the variable with the nametrimmed_fave_phrase like so: fave_phrase = " Hello World " trimmed_fave_phrase = fave_phrase.strip() print(trimmed_fave_phrase) # output Hello World · Now any whitespace at the beginning and end of the string has gone!
Top answer
1 of 14
409

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

2 of 14
89

For Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.

\s on its own always covers the ASCII whitespace:

  • (regular) space
  • tab
  • new line (\n)
  • carriage return (\r)
  • form feed
  • vertical tab

Additionally:

  • for Python 2 with re.UNICODE enabled,
  • for Python 3 without any extra actions,

...\s also covers the Unicode whitespace characters, for example:

  • non-breaking space,
  • em space,
  • ideographic space,

...etc. See the full list here, under "Unicode characters with White_Space property".

However \s DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:

  • zero-width joiner,
  • Mongolian vowel separator,
  • zero-width non-breaking space (a.k.a. byte order mark),

...etc. See the full list here, under "Related Unicode characters without White_Space property".

So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

Sources:

  • https://docs.python.org/2/library/re.html
  • https://docs.python.org/3/library/re.html
  • https://en.wikipedia.org/wiki/Unicode_character_property
🌐
AskPython
askpython.com › python › string › python-remove-spaces-from-string
Python Remove Spaces from String - AskPython
December 29, 2019 - The re.sub() function is used to remove the white-spaces from a string.