简体   繁体   中英

Printing in both double and single quotes

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?

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.'''

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 " .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM