0

I'm trying to understand why python has this unheard of behavior.

If I'm writing rawdata string, it is much more likely that I won't want escaping quotes.

This behavior forces us to write this weird code:

s = r'something' + '\\' instead of just 's = r'something\'

any ideas why python developers found this more sensible?

EDIT:

I'm not asking why it is so. I'm asking what makes this design decision, or if anyone finds any thing good in it.

JoshieSimmons
  • 2,721
  • 2
  • 14
  • 23
Letterman
  • 4,076
  • 5
  • 29
  • 41
  • I'm not asking why it is so. I'm asking what makes this design decision. – Letterman May 30 '14 at 23:04
  • @HuuNguyen or if anyone finds any thing good in it – Letterman May 30 '14 at 23:04
  • 1
    There's a link in that SO question to a faq that explains the decision [here](https://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash). – huu May 30 '14 at 23:06
  • @HuuNguyen wow. This is exactly what I was looking for. I want this to be also documented in SO answer, in case the url breaks. Is it proper to edit my question and put a copy of this paragraph there? – Letterman May 30 '14 at 23:12
  • I added it as an answer to supplement what kindall has already provided. I believe both are useful for people who want to understand your question. – huu May 30 '14 at 23:16

2 Answers2

3

The r prefix for a string literal doesn't disable escaping, it changes escaping so that the sequence \x (where x is any character) is "converted" to itself. So then, \' emits \' and your string is unterminated because there's no ' at the end of it.

kindall
  • 178,883
  • 35
  • 278
  • 309
2

The decision to disallow an unpaired ending backslash in a raw string is explained in this faq:

Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose.

huu
  • 7,032
  • 2
  • 34
  • 49