首页 > 解决方案 > 如何在 Python 中使用 Re 库在括号和字符串之间添加空格?

问题描述

我有 3 个不同的字符串,如果字符串和括号之间没有空格(如果有转义,请勿触摸),我必须在括号前后添加空格。对我来说,它看起来非常复杂的 Re 库,我无法弄清楚。特别是当我使用括号时。

test = "example(test)"
test2 = "example(test)example"
test3 = "(test)example"

我必须在一个重新功能中完成所有这些。

result = re.sub(r"Some code for all of them","Space here",test or test2 or test3)

print(result)

输出

test = "example (test)"
test2 = "example (test) example"
test3 = "(test) example"

我知道它看起来很多,但句尾不应该有空格。

标签: pythonre

解决方案


这是一种方法

import re

test = "example(test)"
test2 = "example(test)example"
test3 = "(test)example"
test4 = "example (test) example"

for i in [test, test2, test3, test4]:
    print(re.sub(r"[^\S]?(\(.*?\))[^\S]?", r" \1 ", i).strip())

输出:

example (test)
example (test) example
(test) example
example (test) example

推荐阅读