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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  遇见更好的自我
    2020-11-22 09:11

    One line of code to remove all extra spaces before, after, and within a sentence:

    sentence = "  The   fox jumped   over    the log.  "
    sentence = ' '.join(filter(None,sentence.split(' ')))
    

    Explanation:

    1. Split the entire string into a list.
    2. Filter empty elements from the list.
    3. Rejoin the remaining elements* with a single space

    *The remaining elements should be words or words with punctuations, etc. I did not test this extensively, but this should be a good starting point. All the best!

提交回复
热议问题