Python raw literal string [duplicate]
Asked Answered
P

2

14
str = r'c:\path\to\folder\'   # my comment
  • IDE: Eclipse
  • Python2.6

When the last character in the string is a backslash, it seems like it will escape the last single quote and treat my comment as part of the string. But the raw string is supposed to ignore all escape characters, right? What could be wrong? Thanks.

Postconsonantal answered 19/8, 2010 at 0:24 Comment(0)
M
36

Raw string literals don't treat backslashes as initiating escape sequences except when the immediately-following character is the quote-character that is delimiting the literal, in which case the backslash does escape it.

The design motivation is that raw string literals really exist only for the convenience of entering regular expression patterns – that is all, no other design objective exists for such literals. And RE patterns never need to end with a backslash, but they might need to include all kinds of quote characters, whence the rule.

Many people do try to use raw string literals to enable them to enter Windows paths the way they're used to (with backslashes) – but as you've noticed this use breaks down when you do need a path to end with a backslash. Usually, the simplest solution is to use forward slashes, which Microsoft's C runtime and all version of Python support as totally equivalent in paths:

s = 'c:/path/to/folder/'

(side note: don't shadow builtin names, like str, with your own identifiers – it's a horrible practice, without any upside, and unless you get into the habit of avoiding that horrible practice one day you'll find yourseld with a nasty-to-debug problem, when some part of your code tramples over a builtin name and another part needs to use the builtin name in its real meaning).

Manilla answered 19/8, 2010 at 0:29 Comment(3)
Slightly different usage but similar question: How does one b64encode() a bytes object with a literal backslash at the end? If I try b'somestring\' I get an error, If I b'somestring\\' it encodes both backslashes.Lyell
This feature of raw strings only enables using \' or \" in RE patterns. Quotes without backslashes, simply ' or " is still not possible. What is even the meaning of \' or \" in a RE pattern? It seems to me the drawbacks of this feature severely outweigh the advantages, even when only used for RE patterns.Kara
I would love to see some concrete examples where Python's raw literals have an advantage over the much simpler "no interpretation done at all".Kara
T
9

It's IMHO an inconsistency in Python, but it's described in the documentation. Go to the second last paragraph:

http://docs.python.org/reference/lexical_analysis.html#string-literals

r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes)

Toponym answered 19/8, 2010 at 0:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.