How to remove all white space in Python

How to remove all white apace in Python

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

sentence = ' newbie  dev'
sentence.strip()
>>> 'newbie  dev'
Remove ALL spaces in a string, even between words:
  • Use str.replace():

    sentence = ' newbie  dev'
    sentence.replace(" ", "")
    >>> 'newbiedev'
  • Use regex

    import re
    sentence = ' newbie  dev'
    sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
Remove ONLY DUPLICATE spaces:
  • Use regex

    sentence = ' hello  apple'
    " ".join(sentence.split())
    >>> 'hello apple'
  • Use str.split():

    import re
    sentence = ' newbie  dev'
    sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
Last modified October 4, 2020