python怎么去除文本多余空格

如题所述

'''
在Python中字符串处理函数里有三个去空格的函数:
strip 同时去掉左右两边的空格
lstrip 去掉左边的空格
rstrip 去掉右边的空格

'''
#具体示例如下:
a=" gho  stwwl "
print(a.lstrip())
print(a.rstrip())
print(a.strip())
#去掉中间多余的空格
s=''
for i in range(len(a)):
    if a[i]==' ' and i<len(a)-1 and a[i+1]==' ':
        continue
    s+=a[i]
print(s)#配合strip()使用,全部多余空格去掉

温馨提示:答案为网友推荐,仅供参考