Python 带变量的三引号字符串[重复]

问题描述 投票:0回答:3

尝试

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)
python file variables
3个回答
2
投票

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

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

myfile.write(template.format(variable))

1
投票

给定的字符串文字是printf-style string。使用

str % arg

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

要使用

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


1
投票

错误

myfile.write(template.format())
不会返回任何您使用
%
运算符连接的内容

最少编辑

您可以完美地使用

%s
。问题是您的括号不匹配,并且括号即
)
应该位于变量之后,如
myfile.write(template.format() % (variable))
中所示。但由于
template.format()
冗余,所以可以忽略。因此正确的方法

myfile.write(template % (variable))

注意:- 任何带有空

format()
且字符串中没有
{}
的字符串都会返回字符串本身

© www.soinside.com 2019 - 2024. All rights reserved.