Unrecognized escape sequences in string literals

Carl Banks pavlovevidence at gmail.com
Sun Aug 9 21:34:14 EDT 2009


On Aug 9, 5:06 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:
> > A friend of mine is just learning Python, and he's a bit tweaked about
> > how unrecognized escape sequences are treated in Python.
> ...
> > In any case, I think my friend should mellow out a bit, but we both
> > consider this something of a wart. He's just more wart-phobic than I am.
> > Is there any way that this behavior can be considered anything other
> > than a wart? Other than the unconvincing claim that you can use this
> > "feature" to save you a bit of typing sometimes when you actually want a
> > backslash to be in your string?
>
> I'd put it this way: a backslash is just an ordinary character, except
> when it needs to be special. So Python's behaviour is "treat backslash as
> a normal character, except for these exceptions" while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".
>
> Why should a backslash in a string literal be an error?

Because the behavior of \ in a string is context-dependent, which
means a reader can't know if \ is a literal character or escape
character without knowing the context, and it means an innocuous
change in context can cause a rather significant change in \.

IOW it's an error-prone mess.  It would be better if Python (like C)
treated \ consistently as an escape character.  (And in raw strings,
consistently as a literal.)

It's kind of a minor issue in terms of overall real-world importance,
but in terms of raw unPythonicness this might be the worst offense the
language makes.


Carl Banks



More information about the Python-list mailing list