Raw strings and escaping

Duncan Booth duncan.booth at invalid.invalid
Tue Oct 3 13:09:22 CEST 2006

"Matthew Warren" <Matthew.Warren at Digica.com> wrote:

> I would expect this to work,
> rawstring=r'some things\new things\some other things\'
> But it fails as the last backslash escapes the single quote.
> ..although writing this I think I have solved my own problem. Is \'
> the only thing escaped in a raw string so you can place ' in a raw
> string? Although I thought the correct thing in that case would be;
> rawstring=r"rawstring'with single-quote"

You cannot end *any* string literal with an odd number of backslash 
characters. The "r" prefix changes how the escape sequences are interpreted 
after the string literal has been parsed, it doesn't change how the literal 
itself is actually parsed. See the Python Reference Manual, 2.4.1:

> When an "r" or "R" prefix is present, a character following a
> backslash is included in the string without change, and all
> backslashes are left in the string. For example, the string literal
> r"\n" consists of two characters: a backslash and a lowercase "n".
> String quotes can be escaped with a backslash, but the backslash
> remains in the string; for example, r"\"" is a valid string literal
> consisting of two characters: a backslash and a double quote; r"\" is
> not a valid string literal (even a raw string cannot end in an odd
> number of backslashes). Specifically, a raw string cannot end in a
> single backslash (since the backslash would escape the following quote
> character). Note also that a single backslash followed by a newline is
> interpreted as those two characters as part of the string, not as a
> line continuation. 

More information about the Python-list mailing list