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()) 是最简单且高效的解决方案。

相关推荐
2501_944521592 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
行思理2 小时前
go语言学习难度及适合学习的人群
开发语言·学习·golang
wangchunyu1143 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
程序 代码狂人4 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
2501_944521595 小时前
Immer 跨端三方库仓颉适配全流程
python·eclipse·django
信誓旦旦的程序猿5 小时前
【Python量化实战宝典 #26】止损与回撤控制手册:移动止损、最大回撤(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
2501_944521595 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
Patrick在香港6 小时前
同一行 strftime,两台机器跑出两种日期
python·datetime·时区·locale·日期处理
2601_967987376 小时前
用Python+OpenCV+YOLO写个游戏脚本:从自动瞄准到自动采集的保姆级教程
python·opencv·yolo·目标检测·游戏自动化
meiying88386 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化