Python how to replace backslash re.sub ()

I have the following line

mystr1 = 'mydirname' myfile = 'mydirname\myfilename' 

I'm trying to do it

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

How to avoid the backslash that I am trying to combine in mystr1?

+6
source share
2 answers

You need a fourfold backslash:

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

Cause:

  • Regular match with one backslash: \\
  • The string to describe this regular expression is: "\\\\" .

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

+16
source

In a regular expression, you can avoid backslash, like any other character, by placing a backslash in front of it. This means that "\\" is a backslash.

0
source

All Articles