我想打印一个字符串加上一个具有指定小数位数的浮点数。在本例中,小数点后3位。
当简单地打印浮点数时,我像这样指定小数位数。
print('%.3f'% x)
上面的结果是我所期望的
然而,当我试图在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
该 %
操作符是一个格式化操作符,这意味着你只需要指定一个字符串,然后用这个操作符将其格式化。
你的字符串 "The value of x is: %.3f"
格式化它 print("The value of x is %.3f" % x)
请注意,对于每个 %
字符串内的值,当使用 %
运营商。
example = "This %s formats %d times" % ("string", 2)
print(example)