Skip to content

[Python] The Method Of String Formatting With Zero Padding And Decimals

No matter which programming language we used to develop, to print out the execution result is needed. Many people used python for data analytics recently, I often confirm my code wrote in the past, too.

Finally, I recorded this simple formatted output note, so that I don’t need to check repeatedly how many damn zeros I missed.

Below, I will record the two formatting methods using {} and % respectively.

However, the official recommendation is to use {} to format the string. After all, the format is clear and has a more flexible filling method than %, such as multiple filling.


Padding Zero In Front Of String

Use zfill() function

It should be noted that the method is only applicable to strings.

If it is to be used for numeric values, it needs to be converted to a string.

Then fill in the number of digit you want. For example, I want to fill up to 5 digits.

a = '777'

print(a.zfill(5))



Output:

00777


Use format() function

This method is not limited to the numeric type or the string. Similarly, the 5 is the number of digits.

a = 777

print('{0:05d}'.format(a))



Output:

00777


Use %

This method can used for numeric value.

a = 777

print('%05d' % a)



Output:

00777

Take A Specific Number Of Decimal Places

Use round() function to round to a specific number of decimal places

We need to pass two arguments into round() function. The former is the value to be rounded, and the latter is the number of decimal places to be taken.

a = 3.1415926

print(round(a, 4))



Output:

3.1416


Use format() function

a = 3.1415926

print('{:.4f}'.format(a))



Output:

3.1416


Use %

a = 3.1415926

print('%.4f' % a)


Output:

3.1416

References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version