Simple question - end a raw string with a single backslash ?

Tony Flury tony.flury at btinternet.com
Tue Oct 13 04:52:39 EDT 2020


I am trying to write a simple expression to build a raw string that ends 
in a single backslash. My understanding is that a raw string should 
ignore attempts at escaping characters but I get this :

     >>> a = r'end\'
       File "<stdin>", line 1
         a = r'end\'
                   ^
    SyntaxError: EOL while scanning string literal

I interpret this as meaning that the \' is actually being interpreted as 
a literal quote - is that a bug ?

If I try to escaped the backslash I get a different problem:

     >>> a = r'end\\'
     >>> a
    'end\\\\'
     >>> print(a)
    end\\
     >>> len(a)
    5
     >>> list(a)
    ['e', 'n', 'd', '\\', '\\']

So you can see that our string (with the escaped backslash)  is now 5 
characters with two literal backslash characters

The only solution I have found is to do this :

     >>> a = r'end' + chr(92)
     >>> a
    'end\\'
     >>> list(a)
    ['e', 'n', 'd', '\\']

or


     >>> a = r'end\\'[:-1]
     >>> list(a)
    ['e', 'n', 'd', '\\']

Neither of which are nice.





More information about the Python-list mailing list