pythonstringescapingbackslashrawstring

How can I put an actual backslash in a string literal (not use it for an escape sequence)?


I have this code:

import os
path = os.getcwd()
final = path +'\xulrunner.exe ' + path + '\application.ini'
print(final)

I want output like:

C:\Users\me\xulrunner.exe C:\Users\me\application.ini

But instead I get an error that looks like:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

I don't want the backslashes to be interpreted as escape sequences, but as literal backslashes. How can I do it?


Note that if the string should only contain a backslash - more generally, should have an odd number of backslashes at the end - then raw strings cannot be used. See How can I print a single backslash?. If you want to avoid the need for escape sequences, see How to write string literals in Python without having to escape them?.


Solution

  • To answer your question directly, put r in front of the string.

    final= path + r'\xulrunner.exe ' + path + r'\application.ini'
    

    More on Python's site here

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters

    But a better solution would be os.path.join:

    final = (os.path.join(path, 'xulrunner.exe') + ' ' +
             os.path.join(path, 'application.ini'))
    

    (I split this across two lines for readability, but you could put the whole thing on one line if you want.)

    I will mention that you can use forward slashes in file paths, and Python will automatically convert them to the correct separator (backslash on Windows) as necessary. So

    final = path + '/xulrunner.exe ' + path + '/application.ini'
    

    should work. But it's still preferable to use os.path.join because that makes it clear what you're trying to do.