21

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?

user838437
  • 1,451
  • 7
  • 23
  • 31
  • 5
    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 May 14 '12 at 14:33
  • @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 May 14 '12 at 14:38
  • 1
    I just thought that what you're doing is almost the same as `os.path.basename(myfile)`. My bad. – Amadan May 14 '12 at 14:42
  • As an aside, be careful about using a single backslash in a string like that; see [DeprecationWarning: invalid escape sequence - what to use instead of \d?](/q/50504500). – Karl Knechtel Aug 05 '22 at 22:57

2 Answers2

44

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"\\"

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 1
    you could also do `newstr = re.sub(mystr1 + re.escape("\\"), "", myfile)`. If your slash is in its own variable `slash = "\\"`, you can `re.sub(mystr1 + re.escape(slash), "", myfile)` – mpag Aug 08 '17 at 19:05
0

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.

TEOUltimus
  • 184
  • 8
  • Yes, but we're dealing with strings here that *contain* a regular expression. Double escaping rules apply. – Tim Pietzcker May 14 '12 at 14:48
  • 1
    and although you might think that r"\" would get you the same as "\\", as r"\\" is "\\\\", you'd be wrong...you can't have a single \ :P – mpag Aug 08 '17 at 20:08