Python how to replace backslash with re.sub()

后端 未结 2 1147
花落未央
花落未央 2020-11-29 09:12

I have the following string

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

I\'m trying to do this

newstr = re.su         


        
相关标签:
2条回答
  • 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.

    0 讨论(0)
  • 2020-11-29 10:13

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

    0 讨论(0)
提交回复
热议问题