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 Fir
Solution 1:
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\)
Solution 2:
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.
Post a Comment for "Escape (insert Backslash) Before Brackets In A Python String"