Backslashes are used for escaping various characters, so to include a literal backslash in your string you need to use "\\"
, for example:
>>> print "testme" + "\\"
testme\
So to add a backslash before each paren in a string you could use the following:
s = s.replace('(', '\\(').replace(')', '\\)')
Or with regular expressions:
import re
s = re.sub(r'([()])', r'\\\1', s)
Note that you can also use a raw string literal by adding a the letter r
before the opening quote, this makes it so that backslash is interpreted literally and no escaping is done. So r'foo\bar'
would be the same as 'foo\\bar'
. So you could rewrite the first approach like the following:
s = s.replace('(', r'\(').replace(')', r'\)')
Note that even in raw string literals you can use a backslash to escape the quotation mark used for the string literal, so r'we\'re'
is the same as 'we\'re'
or "we're"
. This is why raw string literals don't work well when you want the final character to be a backslash, for example r'testme\'
(this will be a syntax error because the string literal is never closed).