Add Leading Zeros to a Number in Python

Padding a number with zeros can be needed for a few reasons, whether it's to make a number look more readable, to make a numeric string easier to sort in a list, or in low-level binary protocols that require packets to be a certain length.

The most obvious way to do this is to concatenate zeros to a numeric string (for more info, check out Concatenate a String and Integer in Python), however, it's not always the most efficient way to do this. There are a number of other methods we'll be looking at here.

zfill

Strings in Python have a zfill method that can be used to pad a string with zeros to a certain length.

>>> "1".zfill(5)
'00001'

The parameter to zfill is the length of the string you want to pad, not necessarily the number of zeros to add. So in the example above, if your string is already 5 characters long, it will not add any zeros.

A few more examples:

>>> "1".zfill(3)
'001'
>>> "12".zfill(3)
'012'
>>> "123".zfill(3)
'123'
>>> "1234".zfill(3)
'1234'
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Note that if you're zero padding an integer (and not a string, like in the previous examples), you'll need to first convert the integer to a string:

>>> str(1).zfill(3)
'001'

f-strings

If you're using Python 3, you can use the f-string syntax to zero pad your strings. This is done using the extra formatting syntax that specifies the number of zeros to add.

>>> f'{1:03}'
'001'

Here the 03 specifies that the string should be padded with 3 zeros. The second digit in this argument is equivalent to the width parameter in the zfill function.

You might also notice that using f-strings, you don't need to explicitly convert your integer to a string, which it will do for you.

>>> f'{123:04}'
'0123'
>>>
>>> num = 99
>>> f'{num:09}'
'000000099'
Last Updated: July 2nd, 2022
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms