gpt4 book ai didi

python - 如何使用 mako 模板进行划分?

转载 作者:太空宇宙 更新时间:2023-11-04 03:56:08 28 4
gpt4 key购买 nike

假设我有两个变量“一”和“二”,它们分别等于 1 和 2。如果可能的话,我怎样才能把它们分成一个 mako 模板?我想要这样的东西:

${"{0:.2f}".format(one/two)}

我要在模板中输出的结果是:0.50

我正在使用 python 2.x。

最佳答案

您需要将 division 添加到 Templatefuture_imports 参数:

>>> from mako.template import Template
>>> print Template("${a/b}").render(a=1, b=2)
0
>>> print Template("${a/b}", future_imports=['division']).render(a=1, b=2)
0.5
>>> print Template("${'{0:.2f}'.format(a/b)}", future_imports=["division"]).render(a=1, b=2)
0.50

引自 docs :

future_imports – String list of names to import from __future__. These will be concatenated into a comma-separated string and inserted into the beginning of the template, e.g. futures_imports=['FOO', 'BAR'] results in from __future__ import FOO, BAR. If you’re interested in using features like the new division operator, you must use future_imports to convey that to the renderer, as otherwise the import will not appear as the first executed statement in the generated code and will therefore not have the desired effect.

关于python - 如何使用 mako 模板进行划分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344996/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com