Reputation: 2027
I am having trouble with extra backslashes that appear when I display a raw string. I want the raw string to equal 9.2\\(4\\)4
, but I keep getting 9.2\\\\(4\\\\)4
in the Primary_Image
variable. However, the program prints 9.2\\(4\\)4
.
import re
def Convert_Image_name_for_regex(image):
image = re.sub(r'.*asa|k8.bin.*','',image)
image = image.replace(r"-", r"", 2)
image = image[:1] + r'.' + image[1:]
image = image[:3] + r'\(' + image[3:]
image = image[:6] + r'\)' + image[6:]
return image
Primary_Image = r'asa924-4-k8.bin'
Primary_Image = Convert_Image_name_for_regex(Primary_Image)
print Primary_Image
Upvotes: 0
Views: 980
Reputation: 8103
\\
represents an escaped backslash. If its prints out correctly, it should be just fine!
To explain a little better, there are not two backslashes there. In Python, the backslash is a special character. If you want to treat it as a normal character, you must escape it. Coincidentally, escaping is exactly what the backslash is for. I don't understand why you would want to remove that, and in fact - I don't think you ever could. To enter a backslash on its own would mean that the next character would be escaped. The string "\\"
contains only one character (a literal backslash). The string r"\\"
contains two (the escape character, and literal backslash). When printed out or used in any sort of I/O, it should be treated as a single character.
If somehow this second backslash is causing problems, it may be because you're trying to use it as a literal marked with an r
. Just remove this r
when using the string to have Python treat "\\"
as one character as expected.
Upvotes: 2