【问题标题】:How to get rid of repeating variable in str.format?如何摆脱 str.format 中的重复变量?
【发布时间】:2016-02-19 12:48:32
【问题描述】:

我有一个字符串模板,我在代码执行期间使用它来格式化几次,只有一个唯一变量some_var

message_tmpl = '{}. Path  {} cannot be extracted'
some_var = '123'
condition = True # or False...
if condition:
    message = message_tmpl.format('True message', some_var)
else:
    message = message_tmpl.format('False Message', some_var)

我如何改进该流程以避免每次都传递some_var

我尝试在下面运行代码 sn-p 没有成功:

message_tmpl = '{msg}. Path  {some_var} cannot be extracted'.format(some_var=some_var)

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    这可以通过模板的特定格式来完成:将'{}' 传递给模板中的第一个格式:

    message_tmpl = '{}. Path  {} cannot be extracted'.format('{}', some_var)
    

    或者

    message_tmpl = '{msg}. Path  {some_var} cannot be extracted'.format(msg='{}', some_var=some_var)
    

    在以这种方式创建模板后,some_var 的传递应该从下一个格式中删除,并且只有 msg 传递。

    【讨论】:

      【解决方案2】:

      您只需要在{msg} 周围再添加一对大括号,如下所示:

      >>> some_var = '123'
      >>> message_tmpl = '{{msg}}. Path  {some_var} cannot be extracted'.format(some_var=some_var)
      >>> message_tmpl.format(msg='a message')
      'a message. Path  123 cannot be extracted'
      

      一般来说,如果您的模板需要逐渐填充,则需要嵌套大括号。更多演示:

      >>> template = '{} {{}} {{{{}}}}'
      >>> template.format('foo')
      'foo {} {{}}'
      >>> template.format('foo').format('bar')
      'foo bar {}'
      >>> template.format('foo').format('bar').format('baz')
      'foo bar baz'
      

      【讨论】:

        【解决方案3】:

        您也可以使用旧式格式和新式:

        message_tmpl = '{msg}. Path %(some_var)s cannot be extracted' % {'some_var': some_var}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-27
          • 2020-07-30
          • 1970-01-01
          • 2022-01-21
          • 2017-01-19
          相关资源
          最近更新 更多