如何在 Python 中将浮点数格式化为固定宽度 [英] How to format a floating number to fixed width in Python
本文介绍了如何在 Python 中将浮点数格式化为固定宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将浮点数格式化为具有以下要求的固定宽度:
How do I format a floating number to a fixed width with the following requirements:
- 如果 n <则前导零1
- 添加尾随十进制零以填充固定宽度
- 截断超过固定宽度的十进制数字
- 对齐所有小数点
例如:
% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
for number in numbers:
print formatter.format(number)
输出就像
23.2300
0.1233
1.0000
4.2230
9887.2000
推荐答案
for x in numbers:
print "{:10.4f}".format(x)
印刷品
23.2300
0.1233
1.0000
4.2230
9887.2000
花括号内的格式说明符遵循 Python 格式字符串语法.具体来说,在这种情况下,它由以下部分组成:
The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:
- 冒号前的 空字符串 表示将下一个提供的参数带到
format()
"——在这种情况下,x
作为唯一的论点. - 冒号后的
10.4f
部分是 格式规范. f
表示定点符号.10
是要打印的字段的总宽度,由空格填充.4
是小数点后的位数.
- The empty string before the colon means "take the next provided argument to
format()
" – in this case thex
as the only argument. - The
10.4f
part after the colon is the format specification. - The
f
denotes fixed-point notation. - The
10
is the total width of the field being printed, lefted-padded by spaces. - The
4
is the number of digits after the decimal point.
这篇关于如何在 Python 中将浮点数格式化为固定宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文