You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何移除字符串括号内的多余空格?

问题:清理括号内的多余空格(括号数量不固定)

原始字符串:

s = "Wow that is really nice, ( 2.1 ) shows that according to the drawings in ( 1. 1) and a) there are errors."

期望清理后的字符串:

s = "Wow that is really nice, (2.1) shows that according to the drawings in (1.1) and a) there are errors."

尝试的正则代码:

import re

regex = r" (?=[^(]*\))"
s = "Wow that is really nice, ( 2.1 ) shows that according to the drawings in ( 1. 1) and a) there are some errors."
re.sub(regex, "", s)

得到的错误结果:

Wow that is really nice, (2.1) shows that according to the drawings in (1.1)anda) there are some errors.

问题:当括号的开闭数量不固定时,该如何正确清理括号内的多余空格,同时不影响括号外的正常空格?


解决方案

之前的正则错误在于:它会匹配所有后面没有左括号(直到右括号)的空格,这就误删了(1.1)和a)之间的空格(因为这个空格后面的内容到)没有左括号)。

要精准清理括号内的空格,推荐使用正则匹配所有()包裹的内容,再通过回调函数清理内部空格的方式,不管括号数量多少都能适用:

import re

def clean_paren_content(match):
    # 获取匹配到的整个括号内容(比如"( 2.1 )"),去掉其中所有空格
    return match.group(0).replace(" ", "")

s = "Wow that is really nice, ( 2.1 ) shows that according to the drawings in ( 1. 1) and a) there are some errors."
result = re.sub(r"\([^)]*\)", clean_paren_content, s)
print(result)

运行结果:

Wow that is really nice, (2.1) shows that according to the drawings in (1.1) and a) there are some errors.

原理说明

  • 正则\([^)]*\):匹配所有以(开头、)结尾的内容([^)]*表示匹配任意非)的字符,确保只匹配单个括号对,不会跨多个括号)
  • 回调函数clean_paren_content:拿到每个匹配到的括号内容后,直接去掉其中所有空格,再替换回原字符串
  • 这种方式只会处理()内部的空格,完全不会影响括号外的正常空格,不管文本中有多少个括号对都能正确处理

内容的提问来源于stack exchange,提问作者Dennis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:45:37