Python 带变量的三引号字符串

Python Triple-quoted strings with variable

正在尝试 write 到带有变量的文件,但返回错误:

template = """1st header line
second header line
There are people in rooms
and the %s
"""
with  open('test','w') as myfile:
    myfile.write(template.format()) % (variable)

.format method 期望您使用 {} 样式而不是 %s 模板化要填充字符串中的空白。它还希望将内插值作为其参数给出。

template = """1st header line
second header line
There are people in rooms
and the {}
"""

myfile.write(template.format(variable))

给定的字符串文字是 printf-style string。使用 str % arg:

with  open('test', 'w') as myfile:
    myfile.write(template % variable)

要使用 str.format,您应该使用占位符 {}{0} 而不是 %s

错误

myfile.write(template.format()) returns 您没有使用 % 运算符连接

最小编辑

你可以完美地使用 %s 。问题是你的括号不匹配,括号即 ) 应该像 myfile.write(template.format() % (variable)) 一样在你的变量之后。但由于 template.format() 多余的 ,因此可以忽略。因此正确的方法

myfile.write(template % (variable))

注意:- 任何字符串 format() 且字符串中没有 {} returns 字符串本身