【发布时间】:2014-04-08 18:40:14
【问题描述】:
我正在尝试使用带有字符串的“.format”在 for 循环中插入值。这就是我想要做的:
with open('test.txt', 'w') as fout:
for element in range (0, 5):
line1 = 'Icon_{}.NO = Icon_Generic;'.format(element)
fout.write(line1)
当我这样做时,它会窒息。我最好的猜测是它不喜欢直接在 {} 旁边的下划线(“_{}”)。这个对吗?有没有好的解决方法?
我用过这样的东西,它可以工作:
line1 = Icon_Generic.NO = Icon_%02d.NO;\n' % element
但是,如果我想使用“% 元素”来编写大量的多行代码,则效果不佳。
提前致谢!
编辑:尽我所能告诉我我正在使用 Python 3.3
这是我得到的错误(使用 IDLE 3.3.2 shell):
>>> with open('p_text.txt', 'w') as fout:
for element in range(0, 5):
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
fout.write(template)
fout.write('\n\n')
input('press enter to exit')
Traceback (most recent call last):
File "<pyshell#13>", line 3, in <module>
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
ValueError: Single '{' encountered in format string
【问题讨论】:
-
窒息?你有什么错误吗?
-
您使用的是 Python 2.6 或更早版本吗?
-
你说的行应该引发了 SyntaxError...(没有结束引号。)
-
@sberry:不,Python 2.6 也支持
str.format(),但不支持此处格式使用的隐式编号。 -
我冒昧地假设您使用的是 Python 2.6。使用
'Icon_{0}.NO = Icon_Generic;'.format(element)(为您的位置占位符编号)。
标签: python