osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


On 10/13/20, Tony Flury via Python-list <python-list at python.org> wrote:
> 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

Since r'\'' represents a two-character string with a backslash and a
single quote, ending a raw string literal with an odd number of
backslashes requires adding the final backslash using implicit
string-literal concatenation. For example:

    >>> r'some\raw\string''\\'
    'some\\raw\\string\\'

Other ways to get the same result may operate at runtime instead of at
compile time.