Remove all whitespace in a string
Solution 1
If you want to remove leading and ending spaces, use str.strip()
:
sentence = ' hello apple'
sentence.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)
sentence = ' hello apple'
sentence.replace(" ", "")
>>> 'helloapple'
If you want to remove duplicated spaces, use str.split()
:
sentence = ' hello apple'
" ".join(sentence.split())
>>> 'hello apple'
Solution 2
To remove only spaces use str.replace
:
sentence = sentence.replace(' ', '')
To remove all whitespace characters (space, tab, newline, and so on) you can use split
then join
:
sentence = ''.join(sentence.split())
or a regular expression:
import 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
:
sentence = 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.
Solution 3
An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:
Remove ALL spaces in a string, even between words:
import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
Remove spaces in the BEGINNING of a string:
import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)
Remove spaces in the END of a string:
import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)
Remove spaces both in the BEGINNING and in the END of a string:
import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
Remove ONLY DUPLICATE spaces:
import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
(All examples work in both Python 2 and Python 3)
Solution 4
"Whitespace" includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate
:
Python 3
' hello apple '.translate(str.maketrans('', '', ' \n\t\r'))
OR if you want to be thorough:
import string
' hello apple'.translate(str.maketrans('', '', string.whitespace))
Python 2
' hello apple'.translate(None, ' \n\t\r')
OR if you want to be thorough:
import string
' hello apple'.translate(None, string.whitespace)
Solution 5
For removing whitespace from beginning and end, use strip
.
>> " foo bar ".strip()
"foo bar"
![0x12](https://i.stack.imgur.com/aBytn.png?s=256&g=1)
0x12
{Python, Rust, Ada, CI, CD, Blockchain} :: Developer | "Agile Coach" () => Rust in Python.
Updated on July 08, 2022Comments
-
0x12 almost 2 years
I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
def my_handle(self): sentence = ' hello apple ' sentence.strip()
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?
-
lsheng about 10 yearsThe greatness of this function is that it also removes the '\r\n' from the html file I received from Beautiful Soup.
-
Andy Hayden about 9 yearsNote: You don't need to compile step, re.sub (and friends) cache the compiled pattern. See also, Emil's answer.
-
Suzana over 8 yearsThis won't help with Unicode whitespace like
\xc2\xa0
-
don about 8 yearsI like "".join(sentence.split()), this removes all whitespace (spaces, tabs, newlines) from anywhere in sentence.
-
Sarang almost 8 yearsDid not work for "\u202a1234\u202c". Gives the same output: u'\u202a1234\u202c'
-
Emil Stenström almost 8 years@Sarang: Those are not whitespace characters (google them and you'll see) but "General Punctuation". My answer only deals with removing characters classified as whitespace.
-
Maximilian Peters over 7 yearsthe question was too remove all white space which includes tabs and new line characters, this snippet will only remove regular spaces.
-
Yannis Dran over 7 yearsbegginner here. Can someone explain me why print(sentence.join(sentence.split())) results to 'hello hello appleapple'? Just want to understand how code is processed here.
-
Cédric Julien over 7 years@YannisDran check the str.join() documentation, when you call
sentence.join(str_list)
you ask python to join items from str_list withsentence
as separator. -
Cecil Curry about 7 years
"".join(sentence.split())
is indeed the canonical solution, efficiently removing all whitespace rather than merely spaces. Mark Byers' excellent answer should probably have been accepted in lieu of this less applicable answer. -
user405 almost 7 years
ans.translate( None, string.whitespace )
produces onlybuiltins.TypeError: translate() takes exactly one argument (2 given)
for me. Docs says that argument is a translate table, see string.maketrans(). But see comment by Amnon Harel, below. -
user405 almost 7 yearsThanks! Or,
xxx.translate( { ord(c) :None for c in string.whitespace } )
for thoroughness. -
Shogan Aversa-Druesne over 5 years
' hello apple'.translate(str.maketrans('', '', string.whitespace))
Note: its better to make a variable to store the trans-table if you intend to do this multiple times. -
deed02392 about 5 yearspython3:
yourstr.translate(str.maketrans('', '', ' \n\t\r'))
-
CapnShanty over 4 yearsThis is the only solution I see here that removes those damn pesky unicode whitespace characters, thanks fam
-
Rolands.EU over 4 yearsin case of more than 2 whitespaces in the end string, extra
sentence.strip().rstrip()
can help same goes forsentence.strip().lstrip()
for beginnig. Not perfect, but works without the need forre
that's in case simple.strip()
misses them -
Shayan Shafiq over 4 yearsThe question specifically asks for removing all of the whitespace and not just at the ends. Please take notice.
-
handle over 4 yearsI know
re
has been suggested before, but I found that the actual answer to the question title was a bit hidden amongst all the other options. -
Dpedrinha over 3 yearsAlthough this is a good point, this isn't really an answer and should be a comment unless you provide a solution. Would you care to provide a solution for this is exactly what I'm looking for? Cheers
-
Elendurwen over 3 yearsThe solution works but is slightly confusing - when using replace, it returns the string, and doesn't replace in-place, so you need
sentence = sentence.replace(" ", "")
-
Scott almost 3 yearsThis answer is irrelevant to this question
-
PJP over 2 yearsIt helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.
-
Jane Kathambi over 2 years@theTinMan thanks for the recommendation I just added the explanations.