Python:如何将数字格式化为固定宽度?
假设我们有这样的代码:
numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
我想要输出一些数字,并且希望它们的宽度是固定的。为了实现这个效果,我打算通过调整小数点后的位数来达到这样的输出:
0.7653
10.200
100.23
500.98
有没有简单的方法可以做到这一点呢?我尝试了各种 %f
和 %d
的配置,但都没有成功。
2 个回答
5
很遗憾,这个问题没有现成的解决办法。而且,用字符串切片的方法在处理四舍五入和溢出方面也不够好。
所以,看起来我们需要自己写一个这样的函数:
def to_fixed_width(n, max_width, allow_overflow = True, do_round = True):
if do_round:
for i in range(max_width - 2, -1, -1):
str0 = '{:.{}f}'.format(n, i)
if len(str0) <= max_width:
break
else:
str0 = '{:.42f}'.format(n)
int_part_len = str0.index('.')
if int_part_len <= max_width - 2:
str0 = str0[:max_width]
else:
str0 = str0[:int_part_len]
if (not allow_overflow) and (len(str0) > max_width):
raise OverflowError("Impossible to represent in fixed-width non-scientific format")
return str0
这样做的效果:
>>> to_fixed_width(0.7653, 6)
'0.7653'
>>> to_fixed_width(10.2, 6)
'10.200'
>>> to_fixed_width(100.2325, 6)
'100.23'
>>> to_fixed_width(500.9874, 6)
'500.99'
>>> to_fixed_width(500.9874, 6, do_round = False)
'500.98'
更多例子:
>>> to_fixed_width(-0.3, 6)
'-0.300'
>>> to_fixed_width(0.000001, 6)
'0.0000'
>>> to_fixed_width(999.99, 6)
'999.99'
>>> to_fixed_width(999.999, 6)
'1000.0'
>>> to_fixed_width(1000.4499, 6)
'1000.4'
>>> to_fixed_width(1000.4499, 6, do_round = False)
'1000.4'
>>> to_fixed_width(12345.6, 6)
'12346'
>>> to_fixed_width(1234567, 6)
'1234567'
>>> to_fixed_width(1234567, 6, allow_overflow = False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in to_fixed_width
OverflowError: Impossible to represent in fixed-width non-scientific format
>>> to_fixed_width(float('nan'), 6)
'nan'
20
将两个 str.format
/ format
调用结合起来:
numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
>>> for n in numbers:
... print('{:.6s}'.format('{:0.4f}'.format(n)))
... # OR format(format(n, '0.4f'), '.6s')
...
0.7653
10.200
100.23
500.98
或者使用 %
操作符:
>>> for n in numbers:
... print('%.6s' % ('%.4f' % n))
...
0.7653
10.200
100.23
500.98
另外,你还可以使用 切片:
>>> for n in numbers:
... print(('%.4f' % n)[:6])
...
0.7653
10.200
100.23
500.98