Quoting backslashes in Python string literals

Quoting backslashes in Python string literals

Youre being mislead by output — the second approach youre taking actually does what you want, you just arent believing it. 🙂

>>> foo = baz \
>>> foo
baz \
>>> print(foo)
baz 

Incidentally, theres another string form which might be a bit clearer:

>>> print(rbaz )
baz 

Use a raw string:

>>> foo = rbaz 
>>> foo
baz \

Note that although it looks wrong, its 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 printed string):

>>> foo = rbaz 
>>> foo
baz \
>>> print(foo)
baz 

And lets keep going because theres more backslash tricks. If you want to have a backslash at the end of the string and use the method above youll come across a problem:

>>> foo = rbaz 
  File <stdin>, line 1
    foo = rbaz 
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings dont work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = baz \
>>> print(foo)
baz 

However, if youre working with Windows file names, youre 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.

Quoting backslashes in Python string literals

What Harley said, except the last point – its not actually necessary to change the /s into s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open(c:/folder/subfolder/file.txt)

The only time youre likely to need the string normpathed is if youre passing to to another program via the shell (using os.system or the subprocess module).

Leave a Reply

Your email address will not be published.