Unrecognized backslash escapes in string literals

Ben Finney ben+python at benfinney.id.au
Sun Feb 22 21:41:26 EST 2015


Chris Angelico <rosuav at gmail.com> writes:

> In Python, unrecognized escape sequences are treated literally,
> without (as far as I can tell) any sort of warning or anything.

Right. Text strings literals are documented to work that way
<URL:https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str>,
which refers the reader to the language reference
<URL:https://docs.python.org/3/reference/lexical_analysis.html#strings>.

> Why is it that Python interprets them this way, and doesn't even give
> a warning?

Because the interpretation of those literals is unambiguous and correct.

It's unfortunate that MS Windows inherited the incompatible “backslash
is a path separator”, long after backslash was already established in
many programming languages as the escape character.

> Is there a way to enable such warnings/errors?

A warning or error for a correctly formatted literal with an unambiguous
meaning would be an up-Pythonic thing to have.

I can see the motivation, but really the best solution is to learn that
the backslash is an escape character in Python text string literals.

This has the advantage that it's the same escape character used for text
string literals in virtually every other programming language, so you're
not needing to learn anything unusual.

-- 
 \        “The deepest sin against the human mind is to believe things |
  `\           without evidence.” —Thomas Henry Huxley, _Evolution and |
_o__)                                                    Ethics_, 1893 |
Ben Finney




More information about the Python-list mailing list