【问题标题】:Python string formatting - combine named placeholder and float formatter for the same argument?Python字符串格式化 - 将命名占位符和浮点格式化程序结合起来用于同一个参数?
【发布时间】:2018-12-05 14:29:12
【问题描述】:

在 Python 中可以结合以下 2 个概念 - 命名参数和浮点格式?

'{0:.2f}'.format(pi)

'{first} {last}'.format(first='Hodor', last='Hodor!')

https://stackoverflow.com/a/8940627/2230844

https://pyformat.info/#named_placeholders

【问题讨论】:

    标签: python string floating-point formatting string-formatting


    【解决方案1】:
    '{value:.2f}'.format(value=pi)
    

    【讨论】:

    【解决方案2】:
    >>> pi=3.14159
    >>> print('{number:.2f}'.format(number=pi))
    3.14
    >>>
    

    【讨论】:

      【解决方案3】:

      另外值得一提的是 fstrings 的回答:print(f'{pi:.2f}')

      【讨论】:

        猜你喜欢
        • 2011-01-27
        • 2013-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-30
        • 2016-11-26
        • 1970-01-01
        相关资源
        最近更新 更多