【问题标题】:Python: Print string and number with a preferred number of decimal places in the same linePython:在同一行中打印带有首选小数位数的字符串和数字
【发布时间】:2020-05-05 11:01:59
【问题描述】:

我想打印一个字符串加上一个指定小数位数的浮点数。在这种情况下,小数点后 3 位。

当简单地打印浮点数时,我会像这样指定小数位数:

print('%.3f'% x)

以上返回我所期望的。

但是,当尝试将字符串包含到 print() 中时,我收到了语法错误。我就是这样做的:

print("The value of x is: " + str(%.3f'% x))

打印指定小数位数的字符串和浮点数的正确方法是什么?

【问题讨论】:

    标签: python string printing floating-point precision


    【解决方案1】:
    x = 27.0
    print("The value of x is: {:.2f}".format(x))
    

    打印:

    The value of x is: 27.00
    

    这里有很好的解释:https://mkaz.blog/code/python-string-format-cookbook/

    【讨论】:

      【解决方案2】:

      % 运算符是一个格式化运算符,这意味着您只指定一个字符串,您将使用该运算符对其进行格式化:

      你的字符串:"The value of x is: %.3f"

      格式化:print("The value of x is %.3f" % x)

      请注意,对于字符串中的每个 %,在使用 % 运算符时,您将需要尽可能多的值:

      example = "This %s formats %d times" % ("string", 2)
      print(example)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-20
        • 2015-12-30
        • 1970-01-01
        • 2021-07-11
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多