【问题标题】:printf type formating in Python is not returning expected resultPython中的printf类型格式没有返回预期结果
【发布时间】:2018-04-04 08:57:44
【问题描述】:

我想用 2 个十进制数字将数值变量嵌入到字符串中。

代码如下:

x = 121.37890

print("The variable x has the value %.2d, which is surprising" % x)

返回:

The variable x has the value 121, which is surprising

我做错了什么?

【问题讨论】:

    标签: python string python-3.x printf string-formatting


    【解决方案1】:

    参考String format mini language wich 告诉你格式化部分中的说明符是干什么用的。 d

    十进制整数。输出以 10 为底的数字。

    没有数字的整数,f 表示

    固定点。将数字显示为定点数。默认精度为 6。

    # python 2.x - discouraged to use it
    print("The variable x has the value %.2f, which is surprising" % x) 
    
    # explicit format syntax
    print("The variable x has the value {:.2f}, which is surprising".format(x))
    
    #implicit format syntax 
    print(f'The variable x has the value {x:.2f}, which is surprising') 
    

    输出:

    The variable x has the value 121.38, which is surprising
    

    请参阅 PEP-0498 以了解文字字符串插值中的格式(隐式 fromat 语法)。

    可以在文档https://docs.python.org/3.1/library/string.html#format-examples 中查看旧语法与新语法的比较 - 它仍然有效,但您应该使用显式/隐式格式进行切换。

    延伸阅读:Python string formatting: % vs. .format

    【讨论】:

      【解决方案2】:

      让它像

      print("The variable x has the value %.2f, which is surprising" % x)
      

      您必须在格式中使用“定点”而不是“小数”。

      返回:

      The variable x has the value 121.38, which is surprising
      

      【讨论】:

        猜你喜欢
        • 2021-01-27
        • 2015-09-16
        • 2016-06-28
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多