Is there a simple way to remove multiple spaces in a string?

后端 未结 29 1334
星月不相逢
星月不相逢 2020-11-22 08:17

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
相关标签:
29条回答
  • 2020-11-22 09:03

    I have tried the following method and it even works with the extreme case like:

    str1='          I   live    on    earth           '
    
    ' '.join(str1.split())
    

    But if you prefer a regular expression it can be done as:

    re.sub('\s+', ' ', str1)
    

    Although some preprocessing has to be done in order to remove the trailing and ending space.

    0 讨论(0)
  • 2020-11-22 09:03
    sentence = "The   fox jumped   over    the log."
    word = sentence.split()
    result = ""
    for string in word:
       result += string+" "
    print(result)
    
    0 讨论(0)
  • 2020-11-22 09:05

    Solution for Python developers:

    import re
    
    text1 = 'Python      Exercises    Are   Challenging Exercises'
    print("Original string: ", text1)
    print("Without extra spaces: ", re.sub(' +', ' ', text1))
    

    Output:
    Original string: Python Exercises Are Challenging Exercises Without extra spaces: Python Exercises Are Challenging Exercises

    0 讨论(0)
  • 2020-11-22 09:05

    Quite surprising - no one posted simple function which will be much faster than ALL other posted solutions. Here it goes:

    def compactSpaces(s):
        os = ""
        for c in s:
            if c != " " or (os and os[-1] != " "):
                os += c 
        return os
    
    0 讨论(0)
  • 2020-11-22 09:06

    Another alternative:

    >>> import re
    >>> str = 'this is a            string with    multiple spaces and    tabs'
    >>> str = re.sub('[ \t]+' , ' ', str)
    >>> print str
    this is a string with multiple spaces and tabs
    
    0 讨论(0)
  • 2020-11-22 09:08

    " ".join(foo.split()) is not quite correct with respect to the question asked because it also entirely removes single leading and/or trailing white spaces. So, if they shall also be replaced by 1 blank, you should do something like the following:

    " ".join(('*' + foo + '*').split()) [1:-1]
    

    Of course, it's less elegant.

    0 讨论(0)
提交回复
热议问题