Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Add Leading Zeros to a Number in Python?
While working with numbers in Python, it is often necessary to add leading zeros to a number. Adding leading zeros is important when dealing with formatted data, ensuring consistent digit counts, or creating more readable output. In this article, we will explore different methods to add leading zeros to numbers in Python.
Using str.zfill() Method
The zfill() method is the most straightforward approach. It converts the number to a string and pads it with leading zeros to reach the specified width.
Syntax
str(number).zfill(desired_width)
Example
number = 50
desired_width = 5
# Convert number to string and use zfill method
number_str = str(number).zfill(desired_width)
print("Number after leading zeros:", number_str)
Number after leading zeros: 00050
Using rjust() Method
The rjust() method rightjustifies a string and fills the remaining space with a specified character — in this case, zeros.
Example
number = 50
desired_width = 5
number_str = str(number).rjust(desired_width, "0")
print("Number after leading zeros:", number_str)
Number after leading zeros: 00050
Using String Formatting
Python's string formatting syntax allows specifying width and fill characters using the format() method.
Example
number = 50
desired_width = 5
number_str = "{:0>{}}".format(number, desired_width)
print("Number after leading zeros:", number_str)
Number after leading zeros: 00050
The {:0>{}} format specifies: fill with zeros (0), rightalign (>), and use the second argument for width.
Using FString (Python 3.6+)
Fstrings provide the most modern and readable syntax for string formatting with leading zeros.
Example
number = 50
desired_width = 5
number_str = f"{number:0{desired_width}}"
print("Number after leading zeros:", number_str)
Number after leading zeros: 00050
For fstrings, you can also use the shorter syntax f"{number:05}" when the width is fixed.
Comparison
| Method | Readability | Python Version | Best For |
|---|---|---|---|
zfill() |
High | All | Simple zero padding |
rjust() |
Medium | All | Custom fill characters |
format() |
Medium | 2.7+ | Complex formatting |
| Fstring | High | 3.6+ | Modern Python code |
Conclusion
Use zfill() for simple leading zero padding. For modern Python (3.6+), fstrings provide the cleanest syntax. Choose rjust() when you need custom fill characters beyond zeros.
