Why can't Python's raw string literals end with a single backslash?

后端 未结 12 1370
后悔当初
后悔当初 2020-11-22 07:37

Technically, any odd number of backslashes, as described in the documentation.

>>> r\'\\\'
  File \"\", line 1
    r\'\\\'
       ^
Syn         


        
12条回答
  •  無奈伤痛
    2020-11-22 08:19

    I encountered this problem and found a partial solution which is good for some cases. Despite python not being able to end a string with a single backslash, it can be serialized and saved in a text file with a single backslash at the end. Therefore if what you need is saving a text with a single backslash on you computer, it is possible:

    x = 'a string\\' 
    x
    'a string\\' 
    
    # Now save it in a text file and it will appear with a single backslash:
    
    with open("my_file.txt", 'w') as h:
        h.write(x)
    

    BTW it is not working with json if you dump it using python's json library.

    Finally, I work with Spyder, and I noticed that if I open the variable in spider's text editor by double clicking on its name in the variable explorer, it is presented with a single backslash and can be copied to the clipboard that way (it's not very helpful for most needs but maybe for some..).

提交回复
热议问题