Search code examples
pythontext-filesstring-formatting

Python Zero-Padding in Output Text File with "{0:+03f}".format() Not Working


I have created a program that calculates a variable-coefficient regression, and am attempting to output those coefficients to a text file. I am trying to use string formatting to pad zeros in order to have the output file line up correctly. The offending code is shown below:

output.write("N = 1 Regression:\n")
output.write("a    = {0:+03.6f}\n".format(T_fit_N1params[0]))
output.write("b1   = {0:+03.6f}\n".format(T_fit_N1params[1]))
output.write("tau1 = {0:+03.6f}\n".format(T_fit_N1params[2]))
output.write("R2   = {0:+03.6f}\n".format(R2(T_data, T_fit_N1)))

and its output is shown below:

N = 1 Regression:
a    = +11.685376
b1   = +75.493626
tau1 = +2.452343
R2   = +0.978152

I am instead expecting the following:

N = 1 Regression:
a    = +011.685376
b1   = +075.493626
tau1 = +002.452343
R2   = +000.978152

I know this is probably something simple, but I can't seem to figure it out even after visiting the documentation here: https://docs.python.org/3/library/string.html#string-formatting


Solution

  • The first number in the format is the total number of digits (including decimal point and sign), not the number to the left of the decimal point. What you want is:

    output.write("a    = {0:+011.6f}\n".format(T_fit_N1params[0]))
    

    When the total width you specified isn't enough, it is automatically expanded to get everything to fit.