views:

39

answers:

2

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 happening here, especially the '4' in between.

+1  A: 

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.

Bryan McLemore
+2  A: 

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)
SilentGhost
Oh, that's it? Isn't the expanded form more readable then?
Nimbuz
it might be more readable but you might not know what the field width will be
SilentGhost
While more readable, it allows for less flexibility at runtime.
Bryan McLemore
"..but you might not know what the field width will be" << care to elaborate? Thats what I'm not getting, whats the difference except the syntax? Thanks
Nimbuz
@Nimbuz: difference is that `4` is determined at runtime and not hard-coded.
SilentGhost
Aha! So like Bryan says, it can be a variable too that can take input from the user, correct?
Nimbuz
Absolutely, that way the user can decide how many decimal places with which to be annoyed.
Bryan McLemore
Great, thank you both! :)
Nimbuz