3

I am on exercise 8 of Learning Python the Hard Way, and I don't understand why certain lines in a print function are printed in single or double quotes.

The program reads as follows:

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

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

The output is as follows:

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

Why is the third sentence in double quotes and why are the others in single quotes?

Bakuriu
  • 98,325
  • 22
  • 197
  • 231

2 Answers2

2

The formatter is using %r so that each str is printed in quotes. The function that does that defaults to using single quotes as the delimiter, but if it sees a single quote in the string, and no double quotes in the string, it switches to using double quotes as the delimiter.

For example, try:

print "%r" % '''This string has a ' and a " in it.'''
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
2

you are using %r which calls the __repr__ method. what you seem to want is rather %s which calls the __str__ method.

in the string in question you already have a '; thats why repr() gives it out quoted in ".

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111