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 of5. - By contrast,
"-42".rjust(5, "0")andf"{'-42':0>5}"treat"-"as a plain character and produce"00-42"—never use.rjust(width, "0")oron strings that may contain negative numbers.
- Both
- 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.
- If the value is longer than
- Do not pass
dformat code to astr(f"{'42':05d}"raisesValueError):- The
dpresentation type applies only to integers (int). Applying:05dto a string raisesValueError: Unknown format code 'd' for object of type 'str'—uses.zfill(5)orf"{s:0>5}"for strings.
- The
- 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"
- Nest a second pair of braces inside an f-string to supply the padding width dynamically from a variable:
- Binary, hexadecimal, and octal zero-padding (
#06xvs.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), whereasf"{255:04x}"outputs"00ff".
- When formatting hex or binary strings with the
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. |
You must log in or register to comment.
