在Python字符串中的括号前转义(插入反斜杠) [英] Escape (Insert backslash) before brackets in a Python string
问题描述
我需要格式化许多包含相似结构的字符串:
I need to format many strings that contain a similar structure:
u'LastName FirstName (Department / Subdepartment)'
我的愿望是使字符串看起来像这样:
My wish is to get the string to look like this:
u'LastName FirstName \(Department / Subdepartment\)'
意思是我需要在左括号和右括号中添加反斜杠。
Meaning I need to add a backslash to the opening bracket and to the closing bracket.
到目前为止,我是在Python中执行此操作:
So far I am doing this in Python:
displayName = displayName.replace('(', '\(').replace(')', '\)').
哪个似乎还可以,但我只是想知道:
Which seems OK, but I am just wondering:
有没有更Python化的方法?
Is there is a more Pythonic way to do it?
我没有找到正确的方法 Python的String文档,但也许我在错误的地方查找了...
I did not find a proper way Python's String documentation, but maybe I am looking in the wrong place...
推荐答案
您已经找到了最Python化的方法, regex 提供了一种不太可读的解决方案:
You've already found the most Pythonic way, regex provides a not so readable solution:
>>> import re
>>> s = u'LastName FirstName (Department / Subdepartment)'
>>> print re.sub(r'([()])', r'\\\1', s)
LastName FirstName \(Department / Subdepartment\)
这篇关于在Python字符串中的括号前转义(插入反斜杠)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!