How do I use string formatting to show BOTH leading zeros and precision of 3?

[Edit: Gah, beaten again]

'%07.3F'%5

The first number is the total field width.


This took me a second to figure out how to do @nosklo's way but with the .format() and being nested.

Since I could not find an example anywhere else atm I am sharing here.

Example using "{}".format(a)

Python 2

>>> a = 5
>>> print "{}".format('%07.3F' % a)
005.000
>>> print("{}".format('%07.3F' % a))
005.000

Python 3

More python3 way, created from docs, but Both work as intended.

Pay attention to the % vs the : and the placement of the format is different in python3.

>>> a = 5
>>> print("{:07.3F}".format(a))
005.000
>>> a = 5
>>> print("Your Number is formatted: {:07.3F}".format(a))
Your Number is formatted: 005.000

Example using "{}".format(a) Nested

Then expanding that to fit my code, that was nested .format()'s:

print("{}: TimeElapsed: {} Seconds, Clicks: {} x {} "
      "= {} clicks.".format(_now(),
                            "{:07.3F}".format((end -
                                               start).total_seconds()),
                            clicks, _ + 1, ((_ + 1) * clicks),
                            )
      )

Which formats everything the way I wanted.

Result

20180912_234006: TimeElapsed: 002.475 Seconds, Clicks: 25 + 50 = 75 clicks.

Important Things To Note:

  • @babbitt: The first number is the total field width.

  • @meawoppl: This also counts the minus sign!...


The first number is the total number of digits, including decimal point.

>>> '%07.3f' % 5
'005.000'

Important Note: Both decimal points (.) and minus signs (-) are included in the count.