Python 正则表达式:去除字符串中多余空格
要截取字符串中的多个空格而不截取一个空格,可以使用正则表达式来实现。以下是一个示例代码:
import re
def remove_single_spaces(string):
# 使用正则表达式将多个连续的空格替换为一个空格
result = re.sub(r'\s+', ' ', string)
return result
# 测试示例
string = ' Hello World! '
result = remove_single_spaces(string)
print(result)
输出结果为:Hello World!
原文地址: http://www.cveoy.top/t/topic/5Iz 著作权归作者所有。请勿转载和采集!