开发者

Python raw literal string [duplicate]

开发者 https://www.devze.com 2023-01-11 23:43 出处:网络
开发者_如何学编程This question already has answers here: Why can't Python's raw string literals end with a single backslash?
开发者_如何学编程This question already has answers here: Why can't Python's raw string literals end with a single backslash? (13 answers) Closed 5 months ago.
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.


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).


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消