Python 使用正则表达式将多个空格替换为一个空格

方法一:使用 re.sub() 替换连续空白字符

python 复制代码
import re

def replace_multiple_spaces(s):
    # 将一个或多个空白字符替换为单个空格
    pattern = r'\s+'
    return re.sub(pattern, ' ', s)

# 测试
text = "Hello    World   This  is   a    test"
result = replace_multiple_spaces(text)
print(f"原始: {repr(text)}")
print(f"处理后: {repr(result)}")
# 输出: 'Hello World This is a test'

方法二:只替换空格(不包括制表符、换行符)

python 复制代码
import re

def replace_multiple_spaces_only(s):
    # 只将连续的空格替换为单个空格(保留制表符和换行符)
    pattern = r' +'
    return re.sub(pattern, ' ', s)

# 测试
text = "Hello    World\t\tTabbed\n\nNewLine"
result = replace_multiple_spaces_only(text)
print(f"原始: {repr(text)}")
print(f"处理后: {repr(result)}")
# 输出: 'Hello World\t\tTabbed\n\nNewLine'

方法三:更精确的控制

python 复制代码
import re

def normalize_spaces(s, preserve_newlines=True):
    """
    标准化空格
    :param s: 输入字符串
    :param preserve_newlines: 是否保留换行符
    :return: 处理后的字符串
    """
    if preserve_newlines:
        # 先按行分割,处理每行的空格,再合并
        lines = s.split('\n')
        processed_lines = [re.sub(r' +', ' ', line) for line in lines]
        return '\n'.join(processed_lines)
    else:
        # 替换所有连续空白字符为单个空格
        return re.sub(r'\s+', ' ', s)

# 测试
text = """Hello    World
This  is   a    test
With    multiple     spaces"""

result1 = normalize_spaces(text, preserve_newlines=True)
print("保留换行符:")
print(result1)
print()

result2 = normalize_spaces(text, preserve_newlines=False)
print("不保留换行符:")
print(result2)

方法四:同时处理开头和结尾的空格

python 复制代码
import re

def clean_and_normalize_spaces(s):
    """
    清理字符串:去除首尾空格,并将中间多个空格替换为一个空格
    """
    # 先替换连续空白字符为单个空格
    s = re.sub(r'\s+', ' ', s)
    # 去除首尾空格
    return s.strip()

# 测试
text = "   Hello    World   This  is   a    test   "
result = clean_and_normalize_spaces(text)
print(f"原始: {repr(text)}")
print(f"处理后: {repr(result)}")
# 输出: 'Hello World This is a test'

方法五:使用 split() 和 join()(无需正则)

python 复制代码
def replace_spaces_simple(s):
    """
    使用 split() 和 join() 方法替换多个空格
    """
    # split() 默认按空白字符分割,并自动去除空字符串
    # join() 用单个空格连接
    return ' '.join(s.split())

# 测试
text = "Hello    World   This  is   a    test"
result = replace_spaces_simple(text)
print(f"原始: {repr(text)}")
print(f"处理后: {repr(result)}")
# 输出: 'Hello World This is a test'

完整示例对比

python 复制代码
import re

def compare_methods(text):
    print(f"原始文本: {repr(text)}\n")
    
    # 方法1: 正则替换所有空白字符
    result1 = re.sub(r'\s+', ' ', text)
    print(f"方法1 (替换所有空白字符): {repr(result1)}")
    
    # 方法2: 正则只替换空格
    result2 = re.sub(r' +', ' ', text)
    print(f"方法2 (只替换空格): {repr(result2)}")
    
    # 方法3: split/join
    result3 = ' '.join(text.split())
    print(f"方法3 (split/join): {repr(result3)}")
    
    # 方法4: 清理并标准化
    result4 = re.sub(r'\s+', ' ', text).strip()
    print(f"方法4 (清理并标准化): {repr(result4)}")

# 测试
test_text = "  Hello    World\t\tTabbed\n\nNewLine  "
compare_methods(test_text)

输出示例

复制代码
原始文本: '  Hello    World\t\tTabbed\n\nNewLine  '

方法1 (替换所有空白字符): ' Hello World Tabbed NewLine '
方法2 (只替换空格): '  Hello World\t\tTabbed\n\nNewLine  '
方法3 (split/join): 'Hello World Tabbed NewLine'
方法4 (清理并标准化): 'Hello World Tabbed NewLine'

性能对比

python 复制代码
import timeit

text = "Hello    World   This  is   a    test" * 1000

# 方法1: 正则替换所有空白字符
def method1():
    return re.sub(r'\s+', ' ', text)

# 方法2: 正则只替换空格
def method2():
    return re.sub(r' +', ' ', text)

# 方法3: split/join
def method3():
    return ' '.join(text.split())

print("正则替换所有空白字符:", timeit.timeit(method1, number=1000))
print("正则只替换空格:", timeit.timeit(method2, number=1000))
print("split/join方法:", timeit.timeit(method3, number=1000))

推荐方案

  • 最简单高效 :使用 ' '.join(s.split()) - 无需正则,自动处理所有空白字符
  • 需要保留特定字符 :使用 re.sub(r' +', ' ', s) - 只替换空格
  • 需要更精确控制 :使用 re.sub(r'\s+', ' ', s).strip() - 替换所有空白字符并去除首尾空格

根据您的具体需求选择合适的方法。对于大多数情况,' '.join(s.split()) 是最简单且高效的解决方案。

相关推荐
小碗羊肉18 小时前
【JavaWeb | 第七篇】部门管理项目实战
java·开发语言·servlet
维诺菌18 小时前
claude code安装
java·开发语言·ai编程·calude
谙弆悕博士18 小时前
快速学C语言—— 第0章:C语言简介
c语言·开发语言·经验分享·笔记·程序人生·课程设计·学习方法
构建的乐趣18 小时前
测度(Measure)和概率测度(Probability Measure) 测度和度量的区别
python
顶点多余19 小时前
自定义协议、序列化、反序列化实现
java·linux·开发语言·c++·tcp/ip
清水白石00819 小时前
把事故变成护城河:如何设计回归测试,防止“订单重复创建”这类历史 Bug 卷土重来?
python·bug
狐狐生风19 小时前
LangGraph 工具调用集成
python·langchain·prompt·agent·langgraph
风味蘑菇干19 小时前
使用接口定义规范,实现类完成具体逻辑。
java·开发语言
MATLAB代码顾问19 小时前
【智能优化】无穷优化算法(INFO)原理与Python实现
开发语言·python·算法
2401_8332693019 小时前
Java多线程:从入门到进阶
java·开发语言