Python, how can I remove whitespaces from a string?

Posted on 2009-04-27
Last Modified: 2012-05-06
How can I remove whitespaces from a string (two examples below) so that they just have one whitespace between the words or no whitespaces if applied to the third example?

1. 'The       International Association for Computing'
2. 'From    Qubit'
3. '    Test'

Question by:ScriberUK
    LVL 8

    Accepted Solution

    See below for one possible solution, or apply what you learned from the previous question ...

    ... several of pepr's solutions should work fine here as well.
    #!/usr/bin/env python2.5
    s1 = 'The       International Association for Computing'
    s2 = 'From    Qubit'
    s3 = '    Test'
    def remove_ws(s):
        return ' '.join(s.split())
    print remove_ws(s1)
    print remove_ws(s2)
    print remove_ws(s3)

    Open in new window

    LVL 41

    Assisted Solution

    Something like this perhaps?

    >>> import re
    >>> s1 = 'The       International Association for Computing'
    >>> s2 = 'From    Qubit'
    >>> s3 = '    Test'
    >>> def blanks( str ) :
    ...   return re.sub( ' +', ' ', str ).strip()
    >>> blanks( s1 )
    'The International Association for Computing'
    >>> blanks( s2 )
    'From Qubit'
    >>> blanks( s3 )

    Open in new window

    LVL 28

    Assisted Solution

    When using re, it is better to compile the regular expression in advance. The truth is that regular expressions should be used carefully. The snippet below shows only slightly modified solution of HonorGod. The \s means "whitespace" (also \t, \n). The regular expression is compiled during compilation of the script. The strip() is neccessary if you want to remove the leading and trailing whitespaces. It is not possible to combine removal of leading/trailing spaces in one step with the spaces inside the string.

    The LunarNRG solution could also be efficient. The taste matter. If the efficiency is important, you can use the timeit module to measure.

    import re
    def myReplace(s, repl = ' ', rex = re.compile(r'\s+')):
        return rex.sub(repl, s).strip() 
    s1 = 'The       International Association for Computing'
    s2 = 'From    Qubit'
    s3 = '    Test'
    print repr(myReplace(s1))  
    print repr(myReplace(s2))  
    print repr(myReplace(s3))  

    Open in new window


    Author Closing Comment

    Thank you all for your help. I have now read up on join, split and re ;)
    LVL 41

    Expert Comment

    Thank you for the assist, and the points.

    Good luck & have a great day.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
    Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
    Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
    Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    9 Experts available now in Live!

    Get 1:1 Help Now