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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  广开言路
    2020-11-22 08:58

    The fastest you can get for user-generated strings is:

    if '  ' in text:
        while '  ' in text:
            text = text.replace('  ', ' ')
    

    The short circuiting makes it slightly faster than pythonlarry's comprehensive answer. Go for this if you're after efficiency and are strictly looking to weed out extra whitespaces of the single space variety.

提交回复
热议问题