KcFnMi KcFnMi - 1 month ago 9
Python Question

'B': "{:0<4.0f}" | How should I read this?

While studying Pandas Style, I got to the following:

df.style.format("{:.2%}")


Which I understand means, turn every value to 2 decimal places and add a
%
in the end.

Just after that, there is:

df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})


How should I read
'B': "{:0<4.0f}"
?

Answer

This is the "new" formatting string syntax, explained in https://docs.python.org/2/library/string.html#format-specification-mini-language.

  • The first 0 means pad with "0"
  • The < means align to the left (so the number will be followed by a bunch of 0's, e.g. '4' will be formatted as "400000…")
  • The 4 means the minimum width is 4 characters
  • The .0 means the precision is 0, i.e. don't show any decimal parts.
  • The f means the type is a fixed-point number.

Examples:

>>> '{:0<4.0f}'.format(1)
'1000'
>>> '{:0<4.0f}'.format(3.14)
'3000'
>>> '{:0<4.0f}'.format(26)
'2600'
>>> '{:0<4.0f}'.format(77777)
'77777'
>>> '{:0<4.0f}'.format(-3)
'-300'