I'm sure there's a good reason!

Tim Peters tim.one at home.com
Wed Mar 21 17:41:12 EST 2001


[Tim Rowe]
> Can any of the assembled experts explain to me why:
> 	print r"\hello"
> is fine, but
> 	print r"hello\"
> isn't? In other words, why does the backslash escape quotes in a raw
> string? At one level I'm going to guess (without reading the spec) that
> it's because "that's what the spec says", but why? I thought the idea of
> raw strings was that they /didn't/ handle escapes!

The idea of raw strings was to make it easier to create input for systems
that want to do their own backslash escape processing (you can think of the
"r" as meaning "regexp" instead ...).  There's no reason to believe such
systems don't need string-quote characters, but much reason to believe
they'll consider an odd number of trailing backslashes to be an error.  So
r-strings were designed to let you pass escaped quote characters easily, at
the cost of forbidding an odd number of trailing backslashes.

See the FAQ for more info; there are many ways to get an odd number of
trailing backslashes on a string.

if-one-string-gimmick-were-enough-for-all-purposes-there-wouldn't-
    be-two<wink>-ly y'rs  - tim





More information about the Python-list mailing list