Quoting backslashes in Python string literals

前端 未结 4 675
独厮守ぢ
独厮守ぢ 2020-11-22 16:21

I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are eit

4条回答
  •  春和景丽
    2020-11-22 16:56

    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 printed 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 "", 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.

提交回复
热议问题