Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 327
user838437 Avatar asked May 14 '12 14:05

user838437


People also ask

How do you use the RE sub function in Python?

re. sub() function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The sub-string to replace. The sub-string to replace with.

What does re sub () do?

The re. sub() function stands for a substring and returns a string with replaced values. Multiple elements can be replaced using a list when we use this function.

Does re sub replace all occurrences?

By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.


1 Answers

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

like image 147
Tim Pietzcker Avatar answered Sep 19 '22 09:09

Tim Pietzcker