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

后端 未结 29 1904
星月不相逢
星月不相逢 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.

提交回复
热议问题