How do you add leading zeros to a number in Python? What function/method can you use? What’s the trick? …etc. We will answer all similar questions in this article.

There are many ways to do this. Below we’ll list some of them and include the example of code for each way so you can see how the method works.

### Using f-strings

F-strings is a new feature in Python 3.6 that makes string interpolation much easier and more readable.

To use this tool, you must place the letter ‘f‘ before the intended string. In the example below, we have a number with two digits: 22. With the f-strings, we can add leading zeros to this number by using this line of code: f'{num:04}'. This line of code will return a 4-digit number that includes the original number and two leading zeros.

number = 22

result = f'{number:04}'
print(result)  # 0022

Output:

0022

### Using zfill() function

The zfill() function in Python is used to pad a string with zeros on the left side of the string.

Syntax:

str.zfill(width)

Parameters:

• width: The total width after appending.

If you want to display a four-digit number, you can use zfill() to add leading zeros by converting the number to a string and then calling zfill(4). Like this:

number = 22

# Use str() to convert the number to string and zfill() to add leading zeros to number
result = str(number).zfill(4)
print(result)  # 0022

Output:

0022

### Using format() function

We covered the syntax of format() in a previous post. You can read more here.

In this case, the format() function takes two arguments: the formatted number and the output’s desired width. For example, if you want to add two leading zeros to the number 22, you would use the following code: format(22, "04"). This line of code will return a 4-digit number consisting of 22 and 2 leading zeros.

number = 22

result = format(number, '04')
print(result)  # 0022

Output:

0022

### Using the modulus “%” operator

The % sign is also known as the string formatting operator or the interpolation operator. This is one of the old ways to format a string in Python.

When we want to add leading zeros to a number, we can use the modulus “%” operator. For example, if we have a number 22, we can use %04d to format it as 0022. Like this:

number = 22

# Use the % operator to add 2 leading zeros to the number
result = "%04d" % number
print(result)  # 0022

Output:

0022

## Summary

In summary, we have covered four simple methods to add leading zeros to a number in Python. However, in this case, we still recommend using zfill(). This is because zfill() is easier to use than other methods.

Have a beautiful day!

Maybe you are interested: