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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  梦谈多话
    2020-11-22 09:20

    I have my simple method which I have used in college.

    line = "I     have            a       nice    day."
    
    end = 1000
    while end != 0:
        line.replace("  ", " ")
        end -= 1
    

    This will replace every double space with a single space and will do it 1000 times. It means you can have 2000 extra spaces and will still work. :)

提交回复
热议问题