Python gotcha of the day

Thomas Jollans tjol at tjol.eu
Wed Mar 14 05:40:38 EDT 2018


On 2018-03-14 05:08, Steven D'Aprano wrote:
> Explain the difference between these two triple-quoted strings:
> 
> Here is a triple-quoted string containing spaces and a triple-quote:
> 
> py> """ \""" """
> ' """ '
> 
> 
> But remove the spaces, and two of the quotation marks disappear:
> 
> py> """\""""""
> '"'
> 
> 
> If nobody gets the answer, I shall reveal all later.
> 
> (Hint: it is not a bug.)
> 

Ah, subtle!

Initially I thought the first one was being interpreted as

''' """ '''

and the second one as

"" '"' "" ""

which left me rather puzzled as to why the first wasn't being interpreted as

"" ' "' " " ""

but of course that's not what's going on at all. The second one is

'''"''' ""

As to WHY - in both your examples, the literal can be interpreted as a
triple-quoted string, so it is (rather than some combination of
single-quoted strings). And, in both cases, the SHORTEST possible
reading as a triple-quoted string is used.

There, now I can go back to work.

- Thomas




More information about the Python-list mailing list