Search code examples
pythonescaping

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:

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

Which seems OK, but I am just wondering:

Is there is a more Pythonic way to do it?

I did not find a proper way Python's String documentation, but maybe I am looking in the wrong place...


Solution

  • 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\)