Skip to content Skip to sidebar Skip to footer

Add Zeros As Prefix To A Calculated Value Based On The Number Of Digits

I have written an expression which will ask for a user input. Based on the user input, it will calculate a value. If the calculated value is say 1, then I want the value to be conv

Solution 1:

You may use zfill() string method:

str(timestep).zfill(4)

Solution 2:

This is more or less similar to the other answer.

i = 9print("{:05d}".format(i))

Solution 3:

just change the print to use a format string:

print'%04d' % int(timestep)

that will zero fill left, and allow it to show 5 digits without problem

however you cannot use that output in any kind of calculations since converting back to a number will strip the left zeros and possibly use it as an octal number - which will cause a conversion error if there are digits that would not be valid octal i.e. 0397

Solution 4:

Use the string.format() method. The following format specification, '{:04}', says replace that with the argument n from format(n) and then format it, :, with leading zeros, 0, printing at least 4, 4, digits.

Example with numbers of different printed widths:

for n in [1, 12, 123, 1234, 12345, 123456]:
    print('{:04}'.format(n))

Output:

000100120123123412345123456

Post a Comment for "Add Zeros As Prefix To A Calculated Value Based On The Number Of Digits"