Width and Precision using *
I'm learning Python from a book and came across this example:
>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
Don't quite understand what's happe开发者_JS百科ning here, especially the '4' in between.
I think you meant something like this:
>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)
'0.333333, 1, 0.3333'
4
is a wild card value that is used in place of asterisk *
. When expanded it would be equivalent to:
>>> '%f, %2.f, %.4f' % (1/3.0, 1.3, 1/3.0)
There are two syntax errors in the line you posted. 1.3.0 isn't a valid number, and the string isn't closed.
This is a valid version of said string format.
'%f, %2.f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
and outputs:
'0.333333, 0.33, 0.3333'
I couldn't find documentation on %.*f in the official docs. However, it appears that it's parsing the 4 to be how many decimal places you want to do the next argument at.
For example:
'%.*f' % (5, 1/3.0)
returns
'0.33333'
and
'%.*f' % (6, 1/3.0)
returns
'0.333333'
It seems to be a way to offer variable length precision, so you could allow your users to specify it.
精彩评论