6

So I was going through "Learn Python the Hard Way"

and while doing this:

formatter = "%r %r %r %r"

print formatter % (
    "I had this thing.",
    "That you could up right.",
    "But it didn't sing.",
    "So I said goodnight"
)

the output was

'I had this thing.' 'That you could up right.' "But it didn't sing." 'So I said goodnight'

But I'm not sure why the 3rd string has double strings.

eumiro
  • 207,213
  • 34
  • 299
  • 261
Bren
  • 3,516
  • 11
  • 41
  • 73

3 Answers3

8

"a" and 'a' are the same strings, no difference.

The third string contains an apostrophe, so it cannot be represented as 'But it didn't sing.' because that would end the string after didn and raise a SyntaxError.

If you want to represent a string with single quote, you can do it:

"'"

or

'\''

The same with double quote:

'"'

or

"\""

If you have a string with both quotes, you can choose one:

'"\'"

or

"\"'"
eumiro
  • 207,213
  • 34
  • 299
  • 261
2

Because the third string would be 'But it didn't sing' - this would provide a syntax error due to three apostrophes, and furthermore, if fixed logically(putting one more ' in the end which would remove the error), you'd be stuck with two strings - 1. 'But it didn' and 2. 't sing', which is not correct.

So to answer your question, "" provide the exact same function in strings but is used when a syntax error could be caused, such as for words like didn't, couldn't, or the like in the English language.

cbll
  • 6,499
  • 26
  • 74
  • 117
  • FWIW, `'But it didn''t sing'` _is_ valid syntax but it doesn't do what we want because Python treats adjacent string literals as a single string. This also happens if there's whitespace between the string literals. – PM 2Ring Jan 05 '16 at 10:01
1

The third string has a ' character in it, that's why " is used to represent it. Try removing the ' from string #3 and you'll see the representation change to 'string'. The strings are identical, it's just a difference in their representation.

andreas-hofmann
  • 2,378
  • 11
  • 15