Remove all whitespace in a string

2,223,861

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"
Share:
2,223,861
0x12
Author by

0x12

{Python, Rust, Ada, CI, CD, Blockchain} :: Developer | "Agile Coach" () => Rust in Python.

Updated on July 08, 2022

Comments

  • 0x12
    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
    lsheng about 10 years
    The greatness of this function is that it also removes the '\r\n' from the html file I received from Beautiful Soup.
  • Andy Hayden
    Andy Hayden about 9 years
    Note: You don't need to compile step, re.sub (and friends) cache the compiled pattern. See also, Emil's answer.
  • Suzana
    Suzana over 8 years
    This won't help with Unicode whitespace like \xc2\xa0
  • don
    don about 8 years
    I like "".join(sentence.split()), this removes all whitespace (spaces, tabs, newlines) from anywhere in sentence.
  • Sarang
    Sarang almost 8 years
    Did not work for "\u202a1234\u202c". Gives the same output: u'\u202a1234\u202c'
  • Emil Stenström
    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
    Maximilian Peters over 7 years
    the question was too remove all white space which includes tabs and new line characters, this snippet will only remove regular spaces.
  • Yannis Dran
    Yannis Dran over 7 years
    begginner 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
    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 with sentenceas separator.
  • Cecil Curry
    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
    user405 almost 7 years
    ans.translate( None, string.whitespace ) produces only builtins.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
    user405 almost 7 years
    Thanks! Or, xxx.translate( { ord(c) :None for c in string.whitespace } ) for thoroughness.
  • Shogan Aversa-Druesne
    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
    deed02392 about 5 years
    python3: yourstr.translate(str.maketrans('', '', ' \n\t\r'))
  • CapnShanty
    CapnShanty over 4 years
    This is the only solution I see here that removes those damn pesky unicode whitespace characters, thanks fam
  • Rolands.EU
    Rolands.EU over 4 years
    in case of more than 2 whitespaces in the end string, extra sentence.strip().rstrip() can help same goes for sentence.strip().lstrip() for beginnig. Not perfect, but works without the need for re that's in case simple .strip() misses them
  • Shayan Shafiq
    Shayan Shafiq over 4 years
    The question specifically asks for removing all of the whitespace and not just at the ends. Please take notice.
  • handle
    handle over 4 years
    I 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
    Dpedrinha over 3 years
    Although 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
    Elendurwen over 3 years
    The 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
    Scott almost 3 years
    This answer is irrelevant to this question
  • PJP
    PJP over 2 years
    It 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
    Jane Kathambi over 2 years
    @theTinMan thanks for the recommendation I just added the explanations.