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?
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.
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.
By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.
You need a quadruple backslash:
newstr = re.sub(mystr1 + "\\\\", "", myfile)
Reason:
\\
"\\\\"
.Or you can use a raw string, so you only need a double backslash: r"\\"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With