문제

When I do any of these I get the expected results as shown:

>>> '{text:{fill}{align}{width}}'.format(text = 'abcdef', width = 8, fill = '~', align = '^')
'~abcdef~'
>>> '{0:~^8}'.format('abcdef')
'~abcdef~'
>>> '{0:~^8.4}'.format('abcdef')
'~~abcd~~'
>>> '{num:{fill}{align}{width}{type}}'.format(num = 12.34, width = 12, fill = '~', align = '^', type = 'f')
'~12.340000~~'
>>> '{0:~^12.4f}'.format(12.34)
'~~12.3400~~~'

However, when I specify precision dynamically, I get much wider output than expected:

>>> '{text:{fill}{align}{width}{precision}}'.format(text = 'abcdef', width = 8, fill = '~', align = '^', precision = .4)
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~abcd~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
>>> '{num:{fill}{align}{width}{precision}{type}}'.format(num = 12.34, width = 12, fill = '~', align = '^', type = 'f', precision = .4) 
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12.3400~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'

Am I doing something wrong or have the wrong expectations or is there a bug?

I'm using Python 2.7.3

도움이 되었습니까?

해결책

You need to put the dot in the format string instead of using a decimal value in the assignment to precision.

>>> '{text:{fill}{align}{width}.{precision}}'.format(text = 'abcdef', width=8, fill = '~', align = '^', precision = 4)
'~~abcd~~'
>>> '{num:{fill}{align}{width}.{precision}{type}}'.format(num = 12.34, width=12, fill = '~', align = '^', type = 'f', precision = 4)
'~~12.3400~~~'

Otherwise, without the dot, width and the string representation of precision (.4 becomes '0.4') get concatenated as strings and the integer portion of the result is used as the width. So, in one of your examples where width is 8 and precision is .4, the resulting width becomes 80 (from truncating 80.4).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top