【问题标题】:Printing in both double and single quotes用双引号和单引号打印
【发布时间】:2015-11-17 03:56:51
【问题描述】:

我正在学习 Python the Hard Way 的 exercise 8,我不明白为什么 print 函数中的某些行用单引号或双引号打印。

程序如下:

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

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

【问题讨论】:

    标签: python quotes double-quotes single-quotes


    【解决方案1】:

    您正在使用%r,它调用__repr__ 方法。您似乎想要的是 %s,它调用了 __str__ 方法。

    在有问题的字符串中,您已经有一个';这就是为什么repr()" 中引用它。

    【讨论】:

    • OP 的问题是为什么引号不同,而不是为什么引号在那里。
    【解决方案2】:

    formatter 使用的是%r,因此每个str 都被打印在引号中。执行此操作的函数默认使用单引号作为分隔符,但如果它在字符串中看到单引号,并且在字符串中没有双引号,它会切换到使用双引号作为分隔符。

    例如,试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2013-12-14
      • 2013-02-16
      • 2013-08-25
      • 2011-01-23
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多