Python:在同一行中打印具有首选小数位数的字符串和数字

Python: Print string and number with a preferred number of decimal places in the same line

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

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

print('%.3f'% x)

以上returns我所期望的

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

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

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

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/

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

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

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

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

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