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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  闹比i
    闹比i (楼主)
    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.

提交回复
热议问题