To convert an integer to a string with leading zeros in Python, the easiest way is with the str() function and + operator.
integer = 123
print("000" + str(integer))
#Output:
000123
You can also use the Python string rjust() function to add leading zeros to a number after converting it to a string.
integer = 123
print(str(integer).rjust(6,"0"))
#Output:
000123
One last way is with the format() function.
integer = 123
print("{:>06}".format(str(integer)))
#Output:
000123
When working with integers, the ability to easily modify the values of the variables easily is valuable.
One such situation is when you have a integer and want to convert it to a string and leading zeros to the string.
Many times, when you are working with data which has an ID or a record number which is represented with a number, you need to add leading zeros to maintain data integrity.
To add leading zeros to a string in Python, the easiest way is with +. In this case, you aren’t worried about length, you know how many zeros you want, and you just want to add leading zeros to your string.
Below is an example showing you how to add leading zeros with string concatenation in Python.
integer = 123
print("000" + str(integer))
#Output:
000123
Using rjust() Function to Add Leading Zeros to String in Python
Another way you can convert an integer to a string and add leading zeros in Python is with the rjust() function.
rjust() takes two parameters. The first is the length of the new string that rjust() will create and the second parameter is the character to add to the left of the string.
Adding leading zeros with rjust() is more useful if you want to get a specific length for your new string and don’t always know the length of the string variable you are using.
Below is an example of adding leading zeros to a string that is a number with rjust() in Python.
integer = 123
print(str(integer).rjust(6,"0"))
#Output:
000123
Using format() Function to Add Leading Zeros to String in Python
One last way you can convert an integer to a string and add leading zeros in Python is with the Python string format() function.
The correct format to use has the form “{:>0N}” where N is the length of the new string you want to create, ‘0’ is for zero, and ‘>’ is for leading.
Using this method is similar to the method with rjust() because here you could easily add leading zeros to a collection of integers after string conversion to make all of the strings have the same length.
Below is the example showing you how to use format() in Python to add leading zeros to an integer after converting it to a string.
integer = 123
print("{:>06}".format(str(integer)))
#Output:
000123
Hopefully this article has been useful for you to learn how to convert an integer to a string and add leading zeros in Python.