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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  庸人自扰
    2020-11-22 08:54

    Similar to the previous solutions, but more specific: replace two or more spaces with one:

    >>> import re
    >>> s = "The   fox jumped   over    the log."
    >>> re.sub('\s{2,}', ' ', s)
    'The fox jumped over the log.'
    

提交回复
热议问题