尝试
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)
给定的字符串文字是printf-style string。使用
str % arg
:
with open('test', 'w') as myfile:
myfile.write(template % variable)
str.format
,您应该使用占位符 {}
或 {0}
而不是 %s
。
myfile.write(template.format())
不会返回任何您使用 %
运算符连接的内容
您可以完美地使用
%s
。问题是您的括号不匹配,并且括号即 )
应该位于变量之后,如 myfile.write(template.format() % (variable))
中所示。但由于template.format()
是冗余,所以可以忽略。因此正确的方法是
myfile.write(template % (variable))
注意:- 任何带有空
format()
且字符串中没有 {}
的字符串都会返回字符串本身