Quoting backslashes in Python string literals
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
Incidentally, there's another string form which might be a bit clearer:
>>> print(r'baz "\"')
baz "\"
Use a raw string:
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
Note that although it looks wrong, it's actually right. There is only one backslash in the string foo
.
This happens because when you just type foo
at the prompt, python displays the result of __repr__()
on the string. This leads to the following (notice only one backslash and no quotes around the print
ed string):
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:
>>> foo = r'baz \'
File "<stdin>", line 1
foo = r'baz \'
^
SyntaxError: EOL while scanning single-quoted string
Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:
>>> foo = 'baz \\'
>>> print(foo)
baz \
However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath()
function:
myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)
This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.