Escape (Insert backslash) before brackets in a Python string

Question:

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…

Asked By: oz123

||

Answers:

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)
Answered By: jamylak

you can use 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.

Answered By: Serdalis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.