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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 09:17

    I have to agree with Paul McGuire's comment. To me,

    ' '.join(the_string.split())
    

    is vastly preferable to whipping out a regex.

    My measurements (Linux and Python 2.5) show the split-then-join to be almost five times faster than doing the "re.sub(...)", and still three times faster if you precompile the regex once and do the operation multiple times. And it is by any measure easier to understand -- much more Pythonic.

提交回复
热议问题