【问题标题】:Python - .format with {} touching other characters [duplicate]Python - .format 与 {} 接触其他字符[重复]
【发布时间】: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


【解决方案1】:

这是给您带来问题的最后一个左大括号,如错误消息所示:“遇到单个 '{'”。如果您需要格式化字符串中的文字花括号,则必须通过将它们加倍 ('{{') 来转义它们,只要它们是文字:

template = """if (!Icon_{0}.notFirstScan) {{""".format(element)
                                          ^ escape the literal '{'

请注意,右花括号 (}) 也是如此!

>>> print('{{{0}}}'.format('text within literal braces'))
{text within literal braces}

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 2016-11-05
    • 2023-03-29
    • 1970-01-01
    • 2016-01-29
    相关资源
    最近更新 更多