Skip to content

How to Add Leading Zeros to a Number in Python

Learn Python's best methods (f-strings, zfill, format) to pad numbers with leading zeros for fixed-width IDs, timestamps, or file naming with clear examples.

Adding leading zeros to numbers is a common formatting task in Python, whether you're generating fixed-width IDs, formatting dates and times, creating file names with consistent numbering, or displaying binary/hex values. Python provides several clean and efficient ways to pad numbers with zeros.

For example:

  • Input: 11, width 6
  • Output: 000011

F-strings (Python 3.6+) are the most modern, readable, and recommended way to add leading zeros:

num = 42

print(f"{num:06d}")   # Pad to 6 digits
print(f"{num:08d}")   # Pad to 8 digits
print(f"{num:03d}")   # Pad to 3 digits

Output:

000042
00000042
042

Understanding the Format Spec

The format specification {num:06d} breaks down as:

Part Meaning
num The variable to format
0 Fill character (use zeros)
6 Minimum total width
d Format as decimal integer
print(f"{1:03d}")       # 001
print(f"{10:05d}")      # 00010
print(f"{999:03d}")     # 999 (already 3+ digits, no padding needed)
print(f"{1000:03d}")    # 1000 (wider than 3, displayed as-is)

Output:

001
00010
999
1000

Using str.zfill()

The zfill() method pads a string with zeros on the left until it reaches the specified length. It's simple and works directly on strings:

num = 42

padded = str(num).zfill(6)
print(padded)

print("42".zfill(8))
print("7".zfill(3))

Output:

000042
00000042
007

Handling Negative Numbers

zfill() correctly handles negative numbers by placing zeros after the minus sign:

num = -42
print(str(num).zfill(6))

Output:

-00042

Using format()

The format() function provides the same formatting capabilities as f-strings but works in older Python versions:

print(format(1, '03d'))
print(format(42, '06d'))
print(format(999, '08d'))

Output:

001
000042
00000999

You can also use str.format():

print("{:05d}".format(42))
print("{:08d}".format(123))

Output:

00042
00000123

Using rjust()

The rjust() method right-justifies a string within a field of a given width, padding with a specified character (default is space):

num = 42

padded = str(num).rjust(6, '0')
print(padded)

padded_spaces = str(num).rjust(6)
print(f"'{padded_spaces}'")

padded_stars = str(num).rjust(6, '*')
print(padded_stars)

Output:

000042
'    42'
****42

Using the % Operator (Legacy)

The older % formatting operator also supports zero-padding:

num = 42

print("%06d" % num)
print("%03d" % num)
print("%010d" % num)

Output:

000042
042
0000000042

Practical Examples

Formatting File Names

for i in range(1, 6):
    filename = f"image_{i:04d}.png"
    print(filename)

Output:

image_0001.png
image_0002.png
image_0003.png
image_0004.png
image_0005.png

Formatting Timestamps

hours, minutes, seconds = 9, 5, 3

timestamp = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
print(timestamp)

Output:

09:05:03

Generating Fixed-Width IDs

def generate_id(number, prefix="ID", width=6):
    return f"{prefix}-{number:0{width}d}"

for i in [1, 42, 999, 12345]:
    print(generate_id(i))

Output:

ID-000001
ID-000042
ID-000999
ID-012345

Formatting Binary and Hexadecimal Numbers

num = 42

print(f"Binary:      {num:08b}")    # 8-digit binary
print(f"Octal:       {num:06o}")    # 6-digit octal
print(f"Hexadecimal: {num:04x}")    # 4-digit hex (lowercase)
print(f"Hexadecimal: {num:04X}")    # 4-digit hex (uppercase)

Output:

Binary:      00101010
Octal:       000052
Hexadecimal: 002a
Hexadecimal: 002A

Comparison of Methods

Method Syntax Works On Handles Negatives Best For
f-string f"{num:06d}" Numbers ✅ Most use cases (recommended)
zfill() str(num).zfill(6) Strings ✅ Simple string padding
format() format(num, '06d') Numbers ✅ Python < 3.6 compatibility
rjust() str(num).rjust(6, '0') Strings ❌ Padding with non-zero characters
% operator "%06d" % num Numbers ✅ Legacy code

Conclusion

For adding leading zeros in modern Python, f-strings (f"{num:06d}") are the best choice: they're readable, fast, and support dynamic widths.

  • Use zfill() when you're working directly with strings and want a quick, method-based approach.
  • For compatibility with older Python versions, format() provides the same capabilities.

Regardless of the method you choose, leading-zero formatting is essential for creating consistent file names, timestamps, IDs, and formatted displays in your Python applications.

Navigation