简体   繁体   English

用双引号和单引号打印

[英]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. 我正在练习艰难学习Python的练习8 ,我不明白为什么print功能中的某些行用单引号或双引号打印。

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. formatter使用%r以便每个str都用引号打印。 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. 您正在使用调用__repr__方法的%r what you seem to want is rather %s which calls the __str__ method. 你似乎想要的是调用__str__方法的%s

in the string in question you already have a ' ; 在有问题的字符串中你已经有了' ; thats why repr() gives it out quoted in " . 这就是为什么repr()""引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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