当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

在 Python 中的括号和字符串之间添加空格

  1. import re
  2. test = "example(test)"
  3. test2 = "example(test)example"
  4. test3 = "(test)example"
  5. test4 = "example (test) example"
  6. for i in [test, test2, test3, test4]:
  7. print(re.sub(r"[^\S]?(\(.*?\))[^\S]?", r" \1 ", i).strip())

Output:

  1. example (test)
  2. example (test) example
  3. (test) example
  4. example (test) example