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 OverflowIf 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'
To remove only spaces use str.replace:
Use with AIsentence = sentence.replace(' ', '')
To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:
Use with AIsentence = ''.join(sentence.split())
or a regular expression:
Use with AIimport 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:
Use with AIsentence = 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.
How to Remove Spaces From a String in Python (Complete 2026 Guide)
methods to remove spaces from text
python - How to strip all whitespace from string - Stack Overflow
python - How do I trim whitespace from a string? - Stack Overflow
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"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"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: ""
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))
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.
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.UNICODEenabled, - 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
To remove all whitespace surrounding a string, use .strip(). Examples:
Use with AI>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'
Note that str.strip() removes all whitespace characters, including tabs and newlines. To remove only spaces, specify the specific character to remove as an argument to strip:
Use with AI>>> " Hello\n ".strip(" ")
'Hello\n'
To remove only one space at most:
Use with AIdef strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
As pointed out in answers above
Use with AImy_string.strip()
will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .
For more flexibility use the following
- Removes only leading whitespace chars:
my_string.lstrip() - Removes only trailing whitespace chars:
my_string.rstrip() - Removes specific whitespace chars:
my_string.strip('\n')ormy_string.lstrip('\n\r')ormy_string.rstrip('\n\t')and so on.
More details are available in the docs.