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

Sander Sweers sander.sweers at gmail.com
Sat Mar 13 18:59:01 CET 2010


On 13 March 2010 18:33, Ray Parrish <crp at cmc.net> 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.

It is not really there. When you have a single quote in a single quote
string it need to be escaped with a backslash. Simulary a double quote
in a double quote string. The triple quote string does this for you.

When you write the string to a file the backslash will "magically" disappear.

> Now I tiry to escape the single quote.
>
>>>> String = """<a href="http://www.rayslinks.com">Ray\'s Links</a>"""
>>>> String
> '<a href="http://www.rayslinks.com">Ray\'s Links</a>'
>
> Once again the unwanted back slash appears.

See above single quotes in single quote string need to be escaped.

>>>> NewString = """'"""
>>>> NewString
> "'"
> Hmmm, no back slash this time...

Correct, here you have a single quote in a double quote string.

>>>> String = """<a href="http://www.rayslinks.com">Ray""" + """'""" + """s
>>>> Links</a>"""
>>>> String
> '<a href="http://www.rayslinks.com">Ray\'s Links</a>'
>
> Why did quoting the single quote work in NewString when I triple quoted just
> the single quote, but not in the other examples where the result shows a
> back slash before my singe quote in String?
>
> Is there a proper way to do this?

You are trying to solve something that is not really a problem. What
is however is your usage of a single quote in html text. You need to
replace it with &#39; or &lsquo;.

Greets
Sander


More information about the Tutor mailing list