编程语言
首页 > 编程语言> > python-用双引号和单引号打印

python-用双引号和单引号打印

作者:互联网

我正在学习“很难学习Python”的exercise 8,但我不明白为什么打印功能中的某些行用单引号或双引号引起来.

该程序的内容如下:

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

输出如下:

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

为什么第三个句子用双引号引起来,为什么其他句子用单引号引起来?

解决方法:

格式化程序使用%r,以便每个str都用引号引起来.该函数默认使用单引号作为定界符,但是如果在字符串中看到单引号,而在字符串中没有双引号,它将切换为使用双引号作为定界符.

例如,尝试:

print "%r" % '''This string has a ' and a " in it.'''

标签:single-quotes,quotes,double-quotes,python
来源: https://codeday.me/bug/20191028/1948648.html