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

相关推荐
a9511416421 小时前
Go 中通过 channel 传递切片时的数据竞争与深拷贝解决方案
jvm·数据库·python
qq_189807031 小时前
如何修改RAC数据库名_NID工具在集群环境下的改名步骤
jvm·数据库·python
zhangchaoxies2 小时前
如何检测SQL注入风险_利用模糊测试技术发现漏洞
jvm·数据库·python
Luca_kill2 小时前
MCP数据采集革命:从传统爬虫到智能代理的技术进化
爬虫·python·ai·数据采集·mcp·webscraping·集蜂云
zhangchaoxies2 小时前
CSS如何实现响应式弹性网格布局_配合media query修改flex-wrap属性
jvm·数据库·python
故事和你913 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
ZC跨境爬虫3 小时前
Scrapy分布式爬虫(单机模拟多节点):豆瓣Top250项目设置与数据流全解析
分布式·爬虫·python·scrapy
sg_knight3 小时前
设计模式实战:命令模式(Command)
python·设计模式·命令模式
石榴树下的七彩鱼3 小时前
图片修复 API 接入实战:网站如何自动去除图片水印(Python / PHP / C# 示例)
图像处理·后端·python·c#·php·api·图片去水印