Reputation: 1501
I have the following string
mystr1 = 'mydirname'
myfile = 'mydirname\myfilename'
I'm trying to do this
newstr = re.sub(mystr1 + "\","",myfile)
How do I escape the backslash I'm trying to concatenate to mystr1?
Upvotes: 22
Views: 30875
Reputation: 184
In a regular expression, you can escape a backslash just like any other character by putting a backslash in front of it. This means "\\" is a single backslash.
Upvotes: 0
Reputation: 336128
You need a quadruple backslash:
newstr = re.sub(mystr1 + "\\\\", "", myfile)
Reason:
\\
"\\\\"
.Or you can use a raw string, so you only need a double backslash: r"\\"
Upvotes: 45