Skip to main content

How to Add Leading Zeros to Numbers in Python

Padding numbers with leading zeros is a common formatting requirement, often used to ensure consistent string lengths for display or data processing.

This guide explores various methods for adding leading zeros to numbers in Python, including str.zfill(), f-strings, str.format(), str.rjust(), and the built-in format() function.

The str.zfill() method is the most straightforward and Pythonic way to pad a number with leading zeros. It's specifically designed for this purpose:

num = 246
result_1 = str(num).zfill(5)
print(result_1) # Output: 00246

result_2 = str(num).zfill(6)
print(result_2) # Output: 000246
  • First convert the number to string using str().
  • zfill(width) pads the string representation of the number with leading zeros until it reaches the specified width.

Handling Signs

str.zfill() correctly handles leading plus (+) or minus (-) signs:

num = -13
result_1 = str(num).zfill(3)
print(result_1) # Output: -13

result_2 = str(num).zfill(4)
print(result_2) # Output: -013
  • The sign is not considered a zero, it will not be padded.

Adding Leading Zeros with f-strings

F-strings provide a concise way to format numbers, including adding leading zeros:

num = 13
result_1 = f'{num:04}'
print(result_1) # Output: 0013

result_2 = f'{num:05}'
print(result_2) # Output: 00013
  • {num:04} formats num as a decimal integer (d is implied and can be omitted), padding with zeros (0) to a total width of 4.
  • f-strings automatically convert the integer to a string.

Using a Variable for Width

You can also use a variable to represent the width:

num = 13
width_of_string = 4
result_1 = f'{num:0{width_of_string}}'
print(result_1) # Output: 0013

Adding Leading Zeros with str.format()

The str.format() method provides similar formatting capabilities:

num = 13
result_1 = '{:04}'.format(num)
print(result_1) # Output: 0013

result_2 = '{:05}'.format(num)
print(result_2) # Output: 00013
  • {:04} represents the same format specifier used with f-strings.

Adding Leading Zeros with str.rjust()

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

num = 13
result_1 = str(num).rjust(4, '0')
print(result_1) # Output: 0013

result_2 = str(num).rjust(5, '0')
print(result_2) # Output: 00013
  • rjust(4, '0') right-justifies the string to a width of 4, padding with '0'.
  • Note that you must convert the number to a string before using rjust().

Adding Leading Zeros with format()

The built-in format() function can also add leading zeros. This is similar to f-strings and str.format:

num = 13

result = format(num, '03')
print(result) # Output: 013

result = format(num, '04')
print(result) # Output: 0013
  • The string format follows the same rule as with f-strings and str.format().
  • The first argument is the value, and the second argument is the formatting string.