17

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,231
  • 6
  • 21
  • 30
  • 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

2 Answers2

36

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
  • 313,408
  • 56
  • 485
  • 544
  • 1
    Not in my Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32: `>>> subject = "is th\is: a path?"; re.sub("[/\\\:?\"]", "_", subject) 'is th_is_ a path_'` – Cees Timmerman Aug 27 '12 at 09:54
  • But i just noticed that only goes for unknown escapes like "\:". – Cees Timmerman Aug 27 '12 at 10:01
  • 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
  • TEOUltimus: your answer is mostly correct; the problem was just a little bit deeper. I'll upvote it so it is at 0 instead of -1. One piece of feedback for the next time: the 'why I hate python' comment is something that is not appreciated on stackoverflow. Stackoverflow is for solid answers, not for mud slinging. – Reinout van Rees May 15 '12 at 02:33
  • 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