Add Leading Zeros to a Number in Python

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?
Project

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms