15
votes

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?

2
I am aware that this does in no way answer your question, but if possible don't even go there; use os.path.join and other os.path functions to manipulate paths in system-independent manner. - Amadan
@Amadan, thanks for you answer, but I'm not trying to manipulate any paths, I'm just trying to take content from a specific file (for that, I'm using os.path) and then I am minifying the data and placing it as a JS var according to the original filename. I'm just manipulating the string of the filename (which includes the full path) for the JS var. - user838437
I just thought that what you're doing is almost the same as os.path.basename(myfile). My bad. - Amadan

2 Answers

35
votes

You need a quadruple backslash:

newstr = re.sub(mystr1 + "\\\\", "", myfile)

Reason:

  • Regex to match a single backslash: \\
  • String to describe this regex: "\\\\".

Or you can use a raw string, so you only need a double backslash: r"\\"

0
votes

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.