在 python 中使用格式化打印的双引号与单引号

Double vs. single quotes using formatted printing in python

所以我正在经历 "Learn Python the Hard Way"

并在执行此操作时:

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

print formatter % (
    "I had this thing.",
    "That you could up right.",
    "But it didn't sing.",
    "So I said goodnight"
)

输出是

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

但我不知道为什么第三根弦有双弦。

"a"'a'是相同的字符串,没有区别。

第三个字符串包含一个撇号,因此它不能表示为 'But it didn't sing.',因为那样会在 didn 之后结束字符串并引发 SyntaxError.

如果你想用单引号表示一个字符串,你可以这样做:

"'"

'\''

与双引号相同:

'"'

"\""

如果您有一个包含两个引号的字符串,您可以选择一个:

'"\'"

"\"'"

第三个字符串里面有一个'字符,所以用"来表示。尝试从字符串 #3 中删除 ',您将看到表示更改为 'string'。字符串是相同的,只是表示形式不同。

因为第三个字符串将是 'But it didn't sing' - 这会由于三个撇号而导致语法错误,而且,如果逻辑上固定(在末尾再放一个 ' 将消除错误),你会被两个字符串卡住 - 1. 'But it didn' 和 2. 't sing',这是不正确的。

因此,为了回答您的问题,"" 在字符串中提供完全相同的功能,但在可能导致语法错误时使用,例如英语中的 didn't、could't 等词语。