The purpose of %02d and %04d

Hello all! I’m new to python and currently stumped on this part of the exercise

From my understanding, the % symbol in python is the modulo operator, it returns the remainder of dividing the left hand number with the right hand number pretty much. It’s used for division problems.

This exercise is asking me to print the current date in the form of mm/dd/yyyy. Simple enough right?

Here’s the thing I can’t understand:
What is the purpose of %02d , and %04d , what does it mean exactly and what does it do in terms of dates? There is no need to use the modulo operator function when it comes to dates as we could just easily print the date as “print dd/mm/yyyy”

Thanks all!

Hi and welcome to the forums!

It is correct that % is the modulo operator when working with numbers, however when working with strings it’s actually the old way of doing string formatting in Python 2. This is covered in the previous section to the one you are in on strings, namely this lesson. If we look at the following piece of code:

print "%02d/%02d/%04d" % (now.month, now.day, now.year)

we can note a few things:

  1. The percent sign in between the string and the terms in brackets tells the python interpreter that we wish to perform string concatenation (as the first element is a string). Explicitly, we are telling it that we want to insert the variables on the right into the string on the left.
  2. When extracting the month, day and year properties from the datetime object, they are numeric variables with a known length (2 for month, 2 for day and 4 for year).

Therefore when we look at the string "%02d/%04d/%04d" we are telling the python interpreter where to place each element in the string. When doing string formatting the variables are always inserted in the order they are positioned, so month then day then year. Therefore we need to tell the interpreter how to actually format these variables when it’s added in. So to quickly break down one of the elements %02d we have.

  • % - This tells the interpreter that a variable should be inserted here.
  • 02 - This tells the interpreter to expect the variable to be 2 in length.
  • d - This tells the interpreter to expect a number, or should we say a"'d’igit".

Therefore what %02d represents is a digit of length 2, and likewise %04d represents a digit of length 4. Hence all this comes together and the above code produces the string, at time of writing, 08/19/2022, which is what we want.

TL;DR

When referring to strings the % operator is a string formatting operator, not the modulo operator. The symbols in the string represent variables to be placed, which are given on the right hand side of the % operator.

5 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.