【问题标题】:Templates with argument in string formatting带有字符串格式参数的模板
【发布时间】:2018-02-14 05:52:03
【问题描述】:

我正在为字符串格式中的模板寻找一个包或任何其他方法(手动替换除外)。

我想实现这样的目标(这只是一个示例,因此您可以了解这个想法,而不是实际的工作代码):

text = "I {what:like,love} {item:pizza,space,science}".format(what=2,item=3)
print(text)

所以输出将是

I love science

我怎样才能做到这一点?我一直在寻找,但找不到任何合适的东西。可能使用了错误的命名术语。


如果周围没有现成可用的包,我很乐意阅读一些关于自己编写代码的起点的提示。

【问题讨论】:

  • 你使用的是 python > 3.6 还是 python
  • 我使用的是可用的最新版本,所以 > 3.6。

标签: python string python-3.x formatting


【解决方案1】:

我认为使用列表就足够了,因为python lists are persistent

what = ["like","love"]
items = ["pizza","space","science"]
text = "I {} {}".format(what[1],items[2])
print(text)

输出: 我爱科学

【讨论】:

    【解决方案2】:

    whatitem 可以使用列表或元组,因为这两种数据类型都保留插入顺序。

    what = ['like', 'love']
    item = ['pizza', 'space', 'science']
    
    text = "I {what} {item}".format(what=what[1],item=item[2])
    print(text)    # I like science
    

    甚至这是可能的。

    text = "I {what[1]} {item[2]}".format(what=what, item=item)
    print(text)  # I like science
    

    希望这会有所帮助!

    【讨论】:

    • 你应该把what[2]item[3]改为what[1]item[2],否则你会得到一个IndexError
    【解决方案3】:

    为什么不用字典?

    options = {'what': ('like', 'love'), 'item': ('pizza', 'space', 'science')}
    print("I " + options['what'][1] + ' ' + options['item'][2])
    

    返回:“我爱科学”

    或者,如果您想要一种方法来摆脱必须重新格式化以容纳/删除空格,然后将其合并到您的字典结构中,如下所示:

    options = {'what': (' like', ' love'), 'item': (' pizza', ' space', ' science'), 'fullstop': '.'}
    print("I" + options['what'][0] + options['item'][0] + options['fullstop'])
    

    这会返回:“我喜欢披萨。”

    【讨论】:

      【解决方案4】:

      由于没有人提供直接回答我的问题的适当答案,我决定自己解决这个问题。

      我必须使用双括号,因为单个括号是为字符串格式保留的。

      我最终获得了以下课程:

      class ArgTempl:
          def __init__(self, _str):
              self._str = _str
      
          def format(self, **args):
              for k in re.finditer(r"{{(\w+):([\w,]+?)}}", self._str,
                                   flags=re.DOTALL | re.MULTILINE | re.IGNORECASE):
                  key, replacements = k.groups()
      
                  if not key in args:
                      continue
      
                  self._str = self._str.replace(k.group(0), replacements.split(',')[args[key]])
      
              return self._str
      

      这是一个原始的 5 分钟编写代码,因此缺乏检查等等。它按预期工作,可以轻松改进。

      在 Python 2.7 & 3.6 上测试~

      用法:

      test = "I {{what:like,love}} {{item:pizza,space,science}}"
      print(ArgTempl(test).format(what=1, item=2))
      > I love science
      

      感谢大家的回复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多