Python raw strings and trailing backslash

It's a FAQ.

And in response to "you really want your string to end with a backslash. There's no way to do that in a 'raw' string.": the FAQ shows how to workaround it.

>>> r'ab\c' '\\' == 'ab\\c\\'
True
>>>

Another way to workaround this is:

 >>> print(r"Raw \with\ trailing backslash\ "[:-1])
 Raw \with\ trailing backslash\

Updated for Python 3 and removed unnecessary slash at the end which implied an escape.

Note that personally I doubt I would use the above. I guess maybe if it was a huge string with more than just a path. For the above I'd prefer non-raw and double up the slashes.


Raw strings are meant mostly for readably writing the patterns for regular expressions, which never need a trailing backslash; it's an accident that they may come in handy for Windows (where you could use forward slashes in most cases anyway -- the Microsoft C library which underlies Python accepts either form!). It's not cosidered acceptable to make it (nearly) impossible to write a regular expression pattern containing both single and double quotes, just to reinforce the accident in question.

("Nearly" because triple-quoting would almost alway help... but it could be a little bit of a pain sometimes).

So, yes, raw strings were designed to behave that way (forbidding odd numbers of trailing backslashes), and it is considered perfectly "proper behavior" for them to respect the design decisions Guido made when he invented them;-).