我想将数字变量嵌入字符串中,并带有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
我做错了什么?
您的建议将不胜感激。
答案 0 :(得分:1)
参见String format mini language的参考资料
告诉你格式化部分中的说明符是什么。 <{p}} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="0" name="cat1" step="1" type="number" value="0" />
<input min="0" name="cat2" step="1" type="number" value="0" />
<input min="0" name="cat3" step="1" type="number" value="0" />
十进制整数。输出基数为10的数字。
没有数字的整数数字,
的d
定点。将数字显示为定点数。默认精度为6.
f
输出:
# 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')
有关文字字符串插值(隐式fromat语法)的格式,请参阅PEP-0498。
可以在文档https://docs.python.org/3.1/library/string.html#format-examples中查看旧语法与新语法的比较 - 它仍然有效,但您应该使用显式/隐式格式进行切换。
答案 1 :(得分:0)
使它像
print("The variable x has the value %.2f, which is surprising" % x)
你必须在格式化中使用“定点”而不是“十进制”。
返回:
The variable x has the value 121.38, which is surprising