What's the point of padding zeroes?


#1

In exercise 4 of the Date and Time lesson, the instructions say to use “%02d” to “pad the dates with zeros in 2 places”. I dont really understand what this does. I also do not understand the use of the “d”. This is confusing me because there was previously an S there instead. Does the D mean that an integer is replacing that instead of a string? Confusing.


#2

Hi @endershot,

the instructions say to use “%02d” to “pad the dates with zeros in 2 places”. I dont really understand what this does.

%02d takes an integer and prints as many zeroes at the front of it as are necessary to make it two characters wide. That way, the exercise can have a date like 08/18/2018 instead of 8/18/2018. It’s more obvious if you use a larger pad number:

>>> foo = 2
>>> bar = 2018
>>> print("%04d\n%04d" % (foo, bar))
0002
2018 # no extra zeroes added because it's already four chars wide

Does the D mean that an integer is replacing that instead of a string?

Yes, that’s correct. Another common one is %f, which is used to print a float.


#3

Besides this helpful information, the padding is also important in statistics. There is a rule saying that statistical information (for example, a mean) should be rounded to the least accurate of its data points. Meaning: the standard deviation of 4, 5.5, 3.6, 9.1, and 7.8 will be rounded to a whole number because 4’s accuracy is only to the whole.
In order to avoid this problem, people will call this number “4.0,” which is treated differently by statistics.
Now, if the numbers were to the nearest hundredth, and we used 4.0, the last place would be in the tenths, which would round the standard deviation to the tenths place. In order to avoid this problem, the number would be called “4.00,” which is different than 4.0 and 4 to statistics.
So padding zeroes is useful because statistics. I’m sure there are other reasons.
Also, the %f thing is a carry-over from the programming language C. Fun fact: Python (at least, the most popular distribution of Python, CPython) is built on C.


#4

Thank you, after thinking for a bit I figured this was what it meant, but it is always good to have confirmation.


#5

This topic is solved.