Skip to main content

How to Add Leading Zeros to a Number in Python

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:

PartMeaning
numThe variable to format
0Fill character (use zeros)
6Minimum total width
dFormat as decimal integer
# More examples
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
tip

If the number already has more digits than the specified width, it's displayed in full (no truncation occurs).

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)

# Works with strings directly too
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
note

zfill() is specifically designed for zero-padding. If the string is already longer than the specified width, it returns the string unchanged.

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)

# Can pad with any character, not just zeros
padded_spaces = str(num).rjust(6)
print(f"'{padded_spaces}'")

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

Output:

000042
' 42'
****42
tip

Use rjust() when you need to pad with characters other than zeros, or when working with strings that aren't necessarily numbers.

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
note

The % formatting style is considered legacy in modern Python. F-strings and format() are preferred for new code, but you'll still encounter % formatting in older codebases.

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
Dynamic width in f-strings

You can use a variable for the width by nesting curly braces:

width = 8
num = 42
print(f"{num:0{width}d}") # 00000042

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

MethodSyntaxWorks OnHandles NegativesBest For
f-stringf"{num:06d}"NumbersMost use cases (recommended)
zfill()str(num).zfill(6)StringsSimple string padding
format()format(num, '06d')NumbersPython < 3.6 compatibility
rjust()str(num).rjust(6, '0')StringsPadding with non-zero characters
% operator"%06d" % numNumbersLegacy 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.