I would like to build on John's helpful answer.
After examining the docs, I've determined that the string will output DOUBLE quotes if it passes DOUBLE the tests:
- Contains a single quote
- Contains NO double quotes
That's the easiest manner to remember it.
The literal "doesn't"
passes the first test because of the apostrophe, which counts as a single quote. Then, we re-examine it and find it does not contain any double quotes inside of the enclosure. Therefore, the string literal outputs as a double quote:
>>> "doesn't"
"doesn't"
There is no need to escape a single quote with a backslash in the output because the enclosure is composed of double quotes!
Now consider the literal '"Isn\'t," they said.'
This literal passes the first test because it contains an apostrophe, even if it's escaped. However, it also contains double quotes, so it fails the second test. Therefore, it outputs as a single quote:
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
And because the enclosure is composed of single quotes, the escape is needed in the output.
If it weren't for the backslash in the output, the EOL (end of line) would have been reached while scanning the literal.
Finally, consider "\"Isn't,\" they said."
There is a single quote inside of the literal, so it does pass the first test...but fails the second. The output should enclose the string literal in single quotes:
>>> "\"Isn't,\" they said."
'"Isn\'t," they said.'
Therefore, the escape is needed to prevent a premature EOL.