How do you pad a string or number with leading zeros in Python? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you pad a string or number with leading zeros in Python?

message-square
0

Use an f-string format specifier (f"{num:05d}" for integers or f"{text:0>5}" for strings) or call s.zfill(width) on a string—both pad values on the left with "0" up to the target width while correctly placing any leading + or - sign before the zeros.

Basic Example

num = 42
neg_num = -42
code = "7A"

# 1. Recommended for integers & floats: f-string zero-padding (`0` + total width)
print(f"{num:05d}")        # Output: "00042"
print(f"{neg_num:05d}")    # Output: "-0042" (sign counts toward the total width of 5)
print(f"{3.14:07.2f}")     # Output: "0003.14" (total width 7, 2 decimal places)

# 2. Recommended for strings: str.zfill(width) or f-string right-alignment (`0>width`)
print(code.zfill(5))       # Output: "0007A"
print(f"{code:0>5}")       # Output: "0007A"
print("-7A".zfill(5))      # Output: "-007A" (zfill keeps leading '+' or '-' before zeros)

Key Details & Edge Cases

  • Sign handling ("-42" $\rightarrow$ "-0042" vs. "00-42"):
    • Both f"{-42:05d}" and "-42".zfill(5) are sign-aware: they place "0" padding after a leading - or + sign ("-0042"), and the sign character counts toward the total target width of 5.
    • By contrast, "-42".rjust(5, "0") and f"{'-42':0>5}" treat "-" as a plain character and produce "00-42"—never use .rjust(width, "0") or 0> on strings that may contain negative numbers.
  • No truncation when the input already meets or exceeds the target width:
    • If the value is longer than width (e.g., f"{123456:04d}" or "123456".zfill(4)), Python returns the full value intact ("123456") without truncating digits.
  • Do not pass d format code to a str (f"{'42':05d}" raises ValueError):
    • The d presentation type applies only to integers (int). Applying :05d to a string raises ValueError: Unknown format code 'd' for object of type 'str'—use s.zfill(5) or f"{s:0>5}" for strings.
  • Dynamic width at runtime (f"{num:0{width}d}"):
    • Nest a second pair of braces inside an f-string to supply the padding width dynamically from a variable:
      width = 6
      print(f"{42:0{width}d}")  # Output: "000042"
      
  • Binary, hexadecimal, and octal zero-padding (#06x vs. 04x):
    • When formatting hex or binary strings with the # prefix (0x / 0b), include the 2 prefix characters in your total width: f"{255:#06x}" outputs "0x00ff" (total length 6), whereas f"{255:04x}" outputs "00ff".

Comparison of Zero-Padding Methods in Python

Method Syntax Accepted Types Sign-Aware (-42 $\rightarrow$ -0042)? Best Used When
F-String Numeric (:0Nd) f"{num:05d}" int (or :0N.Mf for float) Yes Formatting integers, counters, timestamps, or floats with leading zeros.
str.zfill(width) s.zfill(5) str only Yes Padding numeric or alphanumeric strings cleanly with sign awareness.
F-String String (:0>N) f"{s:0>5}" str No ("-42" $\rightarrow$ "00-42") Padding unsigned string identifiers/codes inside a larger f-string template.
str.rjust(width, "0") s.rjust(5, "0") str only No ("-42" $\rightarrow$ "00-42") Padding raw unsigned text or binary bitstrings where +/- has no numeric meaning.
format(val, "05d") format(num, "05d") int, float, str ("0>5") Yes (for numbers) Passing a format specification dynamically as a standalone function call.