【问题标题】:python string formattingpython字符串格式化
【发布时间】:2011-07-28 20:51:18
【问题描述】:

我需要一些有关 Python 的新字符串格式化程序的帮助。基本上,我希望外部花括号不会转义字符串替换字段。

这行得通:

foo = 'bar'
print '{%s}' % foo

但是,这不是:

foo = 'bar'
print('{{0}}'.format(foo))

期望的输出:

'{bar}'

【问题讨论】:

    标签: python string format


    【解决方案1】:

    {{ 是转义的{,但您仍然需要{0} 作为占位符,因此:

    print('{{{0}}}'.format('bar'))
    

    【讨论】:

      【解决方案2】:

      看起来像你想要的:

      >>> foo = 'bar'
      >>> print('{{{0}}}'.format(foo))
      '{bar}'
      

      外部的双倍 {{}} 按字面意思复制到输出,留下 {0} 被解释为替换。

      【讨论】:

      • 哈,有时我倾向于把事情复杂化。谢谢。
      猜你喜欢
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2016-06-21
      相关资源
      最近更新 更多