Add leading zeros to a number in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Add leading zeros to a number in Python #

To add leading zeros to a number:

  1. Use the str() class to convert the number to a string.
  2. Use the str.zfill() method to add leading zeros to the string.
  3. The method takes the width of the string and pads it with leading zeros.
main.py
num = 246 result_1 = str(num).zfill(5) print(result_1) # 👉️ '00246' result_2 = str(num).zfill(6) print(result_2) # 👉️ '000246'

We used the str() class to convert the number to a string.

This is necessary because adding leading zeros to a number causes a SyntaxError.

The str.zfill method takes the width of the string and left-fills the string with 0 digits to make it of the specified width.

main.py
num = 13 result_1 = str(num).zfill(3) print(result_1) # 👉️ '013' result_2 = str(num).zfill(4) print(result_2) # 👉️ '0013'

Converting the number 13 to a string gives us a string with a length of 2.

Passing 3 as the width to the zfill() method, means that the string will get left-filled with a single 0 digit.

The str.zfill() method handles a leading sign prefix (e.g. + or -) by inserting the padding after the sign.

main.py
num = -13 result_1 = str(num).zfill(3) print(result_1) # 👉️ '-13' result_2 = str(num).zfill(4) print(result_2) # 👉️ '-013'

Note that the sign counts towards the width of the string.

If the specified width is less than or equal to the length of the original string, then the original string is returned.

main.py
num = 13 result_1 = str(num).zfill(2) print(result_1) # 👉️ '13' result_2 = str(num).zfill(1) print(result_2) # 👉️ '13'

Alternatively, you can use a formatted string literal to add leading zeros to a number.

main.py
num = 13 result_1 = f'{num:04}' print(result_1) # 👉️ '0013' result_2 = f'{num:05}' print(result_2) # 👉️ '00013'
The first digit after the colon is the fill value, and the second is the width of the string.

We don't have to use the str() class to convert the integer to a string as the conversion is done for us automatically.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.