[Tutor] quoting and escaping

Steve Willoughby steve at alchemy.com
Wed Jan 14 01:07:23 CET 2009


On Tue, January 13, 2009 15:09, Jon Crump wrote:
> All,
>
> Something I don't understand (so what else is new?) about quoting and
> escaping:
>
>>>> s = """ "some" \"thing\" """
>>>> s
> ' "some" "thing" '

Correct.

Note that """ ... """ is just a string constant the same as "..." is, with
the exception that it can easily span multiple physical lines.  What
happens between the quotes, though, is the same.  This includes the fact
that \ is used to escape special characters, so \" is how you can type a
literal " character without it being interpreted as the end-of-string
delimiter.  Of course, since this is a triple-double-quoted string, a
plain old " won't be confused as such anyway, so yes, in this particular
instance they evaluate to the same character when the string object is
created.

To avoid this, you could either escape the backslashes, so you'd have:

s = """ "some" \\"thing\\" """

(now s == ' "some" \"thing\" ')

or, I think better, would be to use raw string constants:

s = r""" "some" \"thing\" """

(now s == ' "some" \"thing\" ')
(note that if you're looking at the representation of s in your
interpreter, it'll actually print as ' "some" \\"thing\\" ', since it's
showing you that the \s are literal.  The actual string value is as
intended, though)






More information about the Tutor mailing list