格式化輸出單個數(shù)字的時候贷屎,可以使用內(nèi)置的 format() 函數(shù)鳍烁,比如:
>>> x = 1234.56789
>>> # Two decimal places of accuracy
>>> format(x, '0.2f')
'1234.57'
>>> # Right justified in 10 chars, one-digit accuracy
>>> format(x, '>10.1f')
' 1234.6'
>>> # Left justified
>>> format(x, '<10.1f')
'1234.6 '
>>> # Centered
>>> format(x, '^10.1f')
' 1234.6 '
>>> # Inclusion of thousands separator
>>> format(x, ',')
'1,234.56789'
>>> format(x, '0,.1f')
'1,234.6'
>>>
如果你想使用指數(shù)記法蔚叨,將f改成e或者E(取決于指數(shù)輸出的大小寫形式)载绿。比如:
>>> format(x, 'e')
'1.234568e+03'
>>> format(x, '0.2E')
'1.23E+03'
>>>
同時指定寬度和精度的一般形式是 '[<>^]?width[,]?(.digits)?' 僻肖, 其中 width 和 digits 為整數(shù),卢鹦?代表可選部分。 同樣的格式也被用在字符串的 format() 方法中劝堪。比如:
>>> 'The value is {:0,.2f}'.format(x)
'The value is 1,234.57'
>>>