【问题标题】:How can I use Py3k-style string formatting within Mako templates?如何在 Mako 模板中使用 Py3k 样式的字符串格式?
【发布时间】:2012-04-22 09:00:50
【问题描述】:

我正在使用 Mako 模板处理 Pyramid 项目,并且我正在尝试显示一些浮点数。这些数字在我的代码中表示为浮点数,但我想将它们截断到小数点后 2 位以显示给用户。众所周知,round() 不是截断浮点数的好方法。由于我只想截断它们以进行显示,因此我倾向于只使用字符串格式而不是使用Decimal 模块的长度。

我发现 an older question here 展示了如何在 Mako 模板中使用 Python 2.x 字符串格式 - 但我如何才能使用 Python 3.x 字符串格式呢?

>>>> "We display two significant digits: {0:.2f}".format(34.567645765)
'We display two significant digits: 34.57'

这可能在文档中和/或可以通过实验发现,但我也想用适用于 Python 3.x 的答案替换旧答案。

【问题讨论】:

    标签: python python-3.x pyramid mako


    【解决方案1】:

    完全一样:

    >>> from mako.template import Template
    >>> Template("We display two significant digits: ${'{0:.2f}'.format(34.567645765)}").render()
    'We display two significant digits: 34.57'
    

    【讨论】:

    • 正确答案在 Stack Overflow:宇宙一切都好。
    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2014-05-29
    • 2011-08-03
    • 2011-01-22
    相关资源
    最近更新 更多