简体   繁体   English

在 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.这意味着我需要在左括号和右括号中添加一个反斜杠。

So far I am doing this in Python:到目前为止,我在 Python 中执行此操作:

  displayName = displayName.replace('(', '\(').replace(')', '\)').

Which seems OK, but I am just wondering:这看起来不错,但我只是想知道:

Is there is a more Pythonic way to do it?有没有更Pythonic的方法来做到这一点?

I did not find a proper way Python's String documentation , but maybe I am looking in the wrong place...我没有找到正确的方法Python 的字符串文档,但也许我找错了地方......

You've already found the most Pythonic way, regex provides a not so readable solution:您已经找到了最 Pythonic 的方式, regex提供了一个不太可读的解决方案:

>>> import re
>>> s = u'LastName FirstName (Department / Subdepartment)'
>>> print re.sub(r'([()])', r'\\\1', s)
LastName FirstName \(Department / Subdepartment\)

you can use re.escape('string') .你可以使用re.escape('string')

example:例子:

import re

escaped = re.escape(u'LastName FirstName (Department / Subdepartment)')

Note:笔记:
This method will return the string with all non-alphanumerics backslashed which includes punctuation and white-space.此方法将返回所有非字母数字反斜杠的字符串,其中包括标点符号和空格。

Though that may be useful for you.虽然这可能对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM