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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  失恋的感觉
    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
    

提交回复
热议问题