Understanding .write line

outputFile.write("%-20s%10.2f\n" % ("Total:", total))

Would anybody mind breaking down the above line? I understand these parts:

outputFile.write: writes text into a .txt document named earlier

... .2f\n"

adds 2 decimal points to the end of the float number that’s outputted

(“Total:”, total) outputs the word Total plus the total amount as determined by the equation above.

The part I’m really trying to understand is:

%-20s%10

I know what this does, but don’t understand how the wording works. I understand that this is formatting but exactly how does this format? Is it twenty spaces after the last letter in the first part? etc. etc.

It is an example of string interpolation. See Built-in Types: printf-style String Formatting.

%-20s is for 20 characters, left-justified.

For a more current formatting technique, see PEP 498 – Literal String Interpolation.

You have two “%” string interpolation codes:

%-20s

%10.2f

The first one ends with an “s”, so it accepts any value and treats it as
a string. The 20 is the width, and the dash - says to align it at the
left, filling the rest of the width with spaces.

The second code ends with an “f”, so it accepts only floats or numbers
that can be converted to float. The total width is 10 and there are two
decimal places shown, as zero if necessary.

1 Like

This was immensely helpful - thank you. In the event that I had wanted to right justify it instead of left justify, would it be
%20s- ?

No. Right alignment is the default:

'%8.2f' % 1.5   # returns '    1.50'
'%-8.2f' % 1.5  # returns '1.50    '


'%8s' % "eggs"  # returns '    eggs'
'%-8s' % "eggs" # returns 'eggs    '

See the documentation here:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

1 Like

Sorry for the late response. Thanks again, as always, Steven!