Python 实际上看到了这一点:
Concatenate the result of
"here is\n"
with the resuslt of
"\t{}\n"
with the result of
"\t{}".format("foo","bar")
您有 3 个单独的字符串文字,只有最后一个应用了 str.format() 方法。
请注意,Python 解释器在运行时连接字符串。
您应该改为使用隐式字符串文字连接。每当您将两个字符串文字并排放置在表达式中 之间没有其他运算符 时,您会得到一个字符串:
"This is a single" " long string, even though there are separate literals"
这与字节码一起存储为单个常量:
>>> compile('"This is a single" " long string, even though there are separate literals"', '', 'single').co_consts
('This is a single long string, even though there are separate literals', None)
>>> compile('"This is two separate" + " strings added together later"', '', 'single').co_consts
('This is two separate', ' strings added together later', None)
来自String literal concatenation documentation:
允许多个相邻的字符串或字节文字(由空格分隔),可能使用不同的引用约定,并且它们的含义与它们的连接相同。因此,"hello" 'world' 等价于"helloworld"。
当您使用隐式字符串文字连接时,末尾的任何.format() 调用都会应用于该整个单个字符串。
接下来,您不想使用\ 反斜杠续行。改用括号,这样更简洁:
temp = (
"here is\n"
"\t{}\n"
"\t{}".format("foo","bar"))
这叫implicit line joining。
您可能还想了解 多行 字符串文字,其中您在开头和结尾使用三个引号。此类字符串中允许换行符并保留为值的一部分:
temp = """\
here is
\t{}
\t{}""".format("foo","bar")
我在 """ 开头后使用了一个 \ 反斜杠来转义第一个换行符。