user838437
user838437

Reputation: 1501

Python how to replace backslash with re.sub()

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

Answers (2)

TEOUltimus
TEOUltimus

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

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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

Upvotes: 45

Related Questions