Steven D'Aprano wrote:
On Sun, 14 Mar 2010 04:33:57 am Ray Parrish wrote:
Hello,

I am getting the following -

 >>> String = """<a href="http://www.rayslinks.com";>Ray's Links</a>"""
 >>> String
'<a href="http://www.rayslinks.com";>Ray\'s Links</a>'

Note the magically appearing back slash in my result string.

You are confusing the printed representation of the string with the contents of the string. The backslash is not part of the string, any more than the leading and trailing quotes are part of the string. They are part of the display of the string.

Consider:

s = "ABC"  # Three characters A B C.
s  # Looks like five?
'ABC'
len(s)  # No, really only three.
3

The quotes are not part of the string, but part of the printable representation. This is supposed to represent what you would type to get the string ABC. You have to type (quote A B C quote).

Now consider:

s = """A"'"B"""  # Five chars A double-quote single-quote d-quote B
s  # Looks like eight?
'A"\'"B'
len(s)  # But actually only five.
5

When printing the representation of the string, Python always wraps it in quotation marks. If the contents include quotation marks as well, Python will escape the inner quotation marks if needed, but remember this is only for the display representation. If you want to see what the string looks like without the external quotes and escapes:

print s
A"'"B


 >>> NewString = """'"""
 >>> NewString

"'"
Hmmm, no back slash this time...

In this case, the string itself only contains a single-quote, no double-quote, so when showing the representation, Python wraps the contents with double-quotes and there is no need to escape the single-quote.

Python's rules for showing the representation of the string includes:

* wrap the string contents in single quotes '
* unless the string contains single quotes, in which case wrap it in double quotes " and display the single quotes unescaped * unless the string contains double quotes as well, in which case wrap it in single quotes and escape the inner single quotes.

But remember: this is only the display of the string, not the contents.
Thank you, that was a very concise description, and has aided my comprehension greatly. Now if I can just keep it separate from the syntax in JavaScript, I'll be doing good. I keep a good record of these forum posts, so I can re-read this if necessary.

Later, Ray Parrish

--
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to