Python:数字的格式化输出

>>> 'The value is {:0,.2f}'.format(x)
'The value is 1,234.57'

需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节。

1.    最简单的控制小数位数

>>> x = 1234.56789
>>> # Two decimal places of accuracy
>>> format(x, '0.2f')
'1234.57'

 2.    右对齐,总共10位,1位小数

>>> format(x, '>10.1f')
'    1234.6'

>>> format(x, '10.1f')
'    1234.6'

3.    左对齐,总共10位,1位小数

>>> format(x, '<10.1f')
'    1234.6'

4.    放中间,总共10位,1位小数

>>> format(x, '^10.1f')
' 1234.6 '

>>> format(x, '^10.2f')
' 1234.67  '

 5.    千位符号

>>> format(x, ',')
'1,234.56789'
>>> format(x, '0,.1f')
'1,234.6

 6.    指数计数法

>>> format(x, 'e')
'1.234568e+03'
>>> format(x, '0.2E')
'1.23E+03'

 7.    例子

>>> 'The value is {:0,.2f}'.format(x)
'The value is 1,234.57'

8.    千位符translate

>>> swap_separators = { ord('.'):',', ord(','):'.' }
>>> format(x, ',').translate(swap_separators)
'1.234,56789'

 9.    %

>>> '%0.2f' % x
'1234.57'
>>> '%10.1f' % x
' 1234.6'
>>> '%-10.1f' % x
'1234.6 '

 这种格式化方法也是可行的,不过比更加先进的format() 要差一点。比如,在使
用% 操作符格式化数字的时候,一些特性(添加千位符) 并不能被支持。

原文地址:https://www.cnblogs.com/baxianhua/p/9896239.html