How to add zeros before a number in Python

In this Python Article, we’ll explore various methods of how to add zeros before a number in Python.

Python Add Zeros Before Number

One common scenario in data processing and manipulation is the need to add leading zeros to a number. For instance, you might have a series of data that you need to standardize with the same number of digits for a report or a system.

Let’s discuss various methods of adding zeros before numbers in Python:

Method 1: Using the Python built-in str.zfill() function

Python’s string method zfill() is a straightforward way to add leading zeros. It takes one argument – the total number of characters you want the string to be. It adds zeros at the beginning of the string until it reaches the desired length.

Example: If we have the state code 5 and we want to ensure it is two digits:

state_code = 5
print(str(state_code).zfill(2)) 

In the above example, we converted the integer to a string with str(state_code) and then used zfill(2) to pad it to two characters with leading zeros.

Output:

python add zeros before number

Method 2: Using Python String formatting

Python string formatting offers a more flexible and powerful way to transform data into strings. The format() function or f-string formatting can be used to add leading zeros.

Example: In a case where you need to prepare a series of numbered reports, and you want all report numbers to have three digits:

report_number = 7
print('{:03d}'.format(report_number))

The :03d inside the curly brackets {} is a format specification for the format function. 0 is the character for padding, 3 is the width or the total number of characters, and d stands for integer.

Output:

add zeros before number in python

If you prefer using f-string formatting:

report_number = 16
print(f"{report_number:03}")

Output:

How to add zeros before a number in Python

Method 3: Using Python rjust() function

The rjust() string method in Python right-justifies the string and fills in the space with a specified character, which is a space by default. In this case, we’ll use ‘0’ as the fill character.

Example: Imagine you have a series of product codes in a retail system, and they need to have a standard length of five digits:

product_code = 57
print(str(product_code).rjust(5, '0'))

This code will print the number right-justified, filling it with zeros up to three characters.

Output:

Python Add Zeros Before Number Example

Conclusion

In Python, there are various ways to add leading zeros to a number, with each method having its own advantages. The zfill() function is easy and straightforward to use for simple padding. The string formatting option offers more power and flexibility, and rjust() can also be used for right-justifying and padding a number.

You may like the following Python tutorials: