Explain Codes LogoExplain Codes Logo

Display number with leading zeros

python
zero-padding
f-strings
string-formatting
Anton ShumikhinbyAnton Shumikhin·Aug 7, 2024
TLDR

Python offers various methods to format integers with leading zeros. str.zfill(5) will prepend zeros until the string length is 5, and "{:05d}" will format an integer with a width of 5 digits, padding the empty spaces with zeros.

# Mr. Zero's doing his z-fill magic here! print("42".zfill(5)) # Output: 00042 # Mr. Format steps in with elegance! print("{:05d}".format(42)) # Output: 00042

Toolkit for zero padding

In Python, there are various shiny tools to display numbers uniformly:

  • f-strings: The cool kid on the block, has been hanging around since Python 3.6. Use f"{value:0width}"
  • str.format(): The age-old reliable. Works everywhere in Python 3. Use "{:0width}".format(value)
  • C-styled % operator: The grumpy grandpa. Recognized equally in Python 2 and 3. Use " %0widthd" % value
  • str.zfill(): The easy goer. Appends zeros on the left to meet the requested length. Use str(value).zfill(width)

Depending on your unique problem, you'll pick your tool.

Handling potential curveballs

As always, with great power( (of formatting methods)) comes great responsibility:

  • Negative integers: Using f"{number:02d}" or "{:02d}".format(number) you might stumble upon negative numbers. Use parentheses to secure them!
  • Size does matter: Remember that str.zfill(width) will not cut down a number which is wider than the width. It can only add, not subtract.
  • ** "Stringy" numbers or floaters**: If you're dealing with non-integer types like floats or strings that are numbers, tailor your handling. f"{value:0.2f}" might come handy for floats by balancing precision and padding.

Formatting in action: real world examples

Wondering how this helps? Let's explore places where our formatting heroes make our lives easier:

  • Mr. ZIP codes: ZIP codes in the US strictly follow the five digits rule. Our friend f-string has got this - f"{zipcode:05d}" to the rescue.
  • Timekeeper: Keeping digital clock time tidy is a tough job, but again f-string saves the day! Use f"{hour:02d}:{minute:02d}".
  • Chef Date-o: Serving dates in the ISO format? Use f"{year}-{month:02d}-{day:02d}".

Looking for more advanced formatting? Python's PEP 3101 is your go-to recipe book!

Upgrading and adapting

While the bright and shiny f-strings offer readability benefits, older codebases might not support Python 3.6+. For such scenarios:

  • Cross-version compatibility: " %02d" % number ensures that padding works regardless of the Python version.
  • Smooth transitions: If upgrading your codebase to use a newer Python version, replace old % formatting with .format() or f-strings.