Add zeros to string with Python is an example that can help you in the event that you are working with string variables and the target system, whether a database or a legacy system, requires that the size of the string match the specified size. That is, for these systems operating with ‘5’ or ‘005’ is totally different.
In this case we are going to start from a string in the following way:
number = '5'
If we print this string we will see that a 5 appears in the console.
print number
# A '5' appears.
Now let’s add zeros to string with Python. For this we are going to use the .zfill() method. This method receives a parameter which will be the size of the string. Taking the value of the current string and filling it with leading zeros until reaching the value indicated in the parameter.
The .zfill() method will be applied directly to the string. That is why if we want its result to persist on the variable we must assign it.
So, what we will do, if we want to insert two zeros in the string, we will use the following code in Python:
number = number.zfill(3)
Now, if we print the string again we will see that ‘005’ appears:
print number
# A '005' appears
In this simple way we will have managed to add zeros to the string with Python and solve our problem with handling variables of a fixed size.
What other cases can you think of where we need to add zeros to a string with Python? Tell us in the comments. They will be of great interest to us.
