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…
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)
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.
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…
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)
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.