Python 中的格式化程序

Formatters in Python

我有这行代码:

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

打印格式化程序 % (1, 2, 3, 4) 打印格式化程序 % ("one", "two", "three", "four") 打印格式器 % (True, False, False, True) 打印格式化程序 %(格式化程序、格式化程序、格式化程序、格式化程序) 打印格式化程序 % ( "I had this thing for you.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." )<<<

最后 4 行的输出是:

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

我想弄明白为什么第三句显示双引号,其他的显示单引号

我已经尝试删除双引号,但没有产生预期的结果。


print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
    "I had this thing for you.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."

这是因为字符串中有撇号 '。如果删除它,它将打印为 'But it didnt sing.' 这是为了区分字符串限制。如果打印成 ' 会有些混乱: 'But it didn't sing.'

PS。如果您将 '" 符号都添加到您的字符串中,那么事情会变得更加有趣。试试你自己。