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

后端 未结 12 1168
后悔当初
后悔当初 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:07

    some tips :

    1) if you need to manipulate backslash for path then standard python module os.path is your friend. for example :

    os.path.normpath('c:/folder1/')

    2) if you want to build strings with backslash in it BUT without backslash at the END of your string then raw string is your friend (use 'r' prefix before your literal string). for example :

    r'\one \two \three'
    

    3) if you need to prefix a string in a variable X with a backslash then you can do this :

    X='dummy'
    bs=r'\ ' # don't forget the space after backslash or you will get EOL error
    X2=bs[0]+X  # X2 now contains \dummy
    

    4) if you need to create a string with a backslash at the end then combine tip 2 and 3 :

    voice_name='upper'
    lilypond_display=r'\DisplayLilyMusic \ ' # don't forget the space at the end
    lilypond_statement=lilypond_display[:-1]+voice_name
    

    now lilypond_statement contains "\DisplayLilyMusic \upper"

    long live python ! :)

    n3on

提交回复
热议问题