繁体   English   中英

带有字符串格式参数的模板

[英]Templates with argument in string formatting

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

我想要实现这样的功能 (这只是一个示例,所以您可以了解其主意,而不是实际的工作代码):

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

因此输出将是

I love science

我该如何实现? 我一直在搜索,但找不到合适的东西。 可能使用了错误的命名术语。


如果周围没有任何准备使用的软件包,我很想阅读一些起点来自己编写代码。

我可以使用列表或元组作为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

希望这可以帮助!

我认为使用列表就足够了,因为python列表是持久的

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

输出:我喜欢科学

为什么不使用字典?

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'])

然后返回:“我喜欢披萨。”

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

我必须使用双括号,因为单引号保留用于字符串格式化。

我完成了以下课程:

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

这是一个原始的,五分钟的书面代码,因此缺少检查等。 它可以按预期工作,并且可以轻松改进。

在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

感谢您的所有答复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM