[Tutor] Escaping a single quote mark in a triple quoted string.

Steven D'Aprano steve at pearwood.info
Sat Mar 13 19:04:28 CET 2010


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.



-- 
Steven D'Aprano


More information about the Tutor mailing list