如何减少 Python 中的空格?

How to reduce whitespace in Python?

如何从

中减少 Python 中的空格

test = ' Good ' 到单个空格 test = ' Good '

我试过定义这个函数,但是当我尝试 test = reducing_white(test) 它根本不起作用,它与函数 return 或其他什么有关吗?

counter = []

def reducing_white(txt):
    counter = txt.count(' ')
    while counter > 2: 
      txt = txt.replace(' ','',1)
      counter = txt.count(' ')
      return txt

我是这样解决的:

def reduce_ws(txt):
    ntxt = txt.strip()
    return ' '+ ntxt + ' '

j = '    Hello World     '
print(reduce_ws(j))

输出:

'你好世界'

您需要使用正则表达式:

import re

re.sub(r'\s+', ' ', test)
>>>> ' Good '

test = '     Good    Sh ow     '
re.sub(r'\s+', ' ', test)
>>>> ' Good Sh ow '

r'\s+' 匹配所有多个空白字符,并用 ' ' 替换整个序列,即单个空白字符。

此解决方案相当强大,适用于多个空间的任意组合。