Formatting output in Python 3

I’ve had to work hard to get ‘pretty’ output from Python: it seems more complicated than with 50-year-old Fortran IV! Fortunately, Python’s formatting procedures have advanced, no doubt trying to resolve some of the issues.  Unfortunately, there are now many ways to do things, and if you search online, each website shows yet another method.

After considerable frustration, I found that Python has a full set of consistent, flexible and simple formatting codes – not a million miles away from those in Fortran!

An example

I want to show clock times in the conventional way such as 12:32 or as 05:09. Note the need for leading zeroes. The moon clock keeps the hours and minutes of the time in separate variables, which are already converted to integers.

To convert an integer value into a string formatted as above, the statement is:
hourString = ‘{0:02}’.format(hourInteger)
If hourInteger = 4, this would produce an output string  04

The format parameter ‘{0:02}’ says ‘convert the numerical value hourInteger into a string representation within a field length of 2 and pad the field with leading zeroes.

Converting a floating point value into a string, might use
clockphaseString = ‘{0:.3f}’.format(clockphase)
This could produce an output like 0.683.  The floating point value is correctly rounded to three decimal places.

clockazString = ‘{0:.0f}’.format(clockaz)
could produce an output like 306 (note that although clockaz is a floating-point value, it is displayed as a whole number).

You can format and insert any number of values from the format list: the ‘0’ at the beginning refers to the position in the value to be inserted.  Supposing the hour is 4 am stored as an integer in variable clockhour and the minute is 9 minutes past the hour, stored in variable clockmin, the following would create the character string 04:09

clocktime= ‘{1:02}:{0:02}’.format(clockmin, clockhour}

Note how the index value (the 1 in {1:02}) is used to correctly reposition the minutes and hours.

I don’t want to put all the detail into this blog, but the system is described well in this tutorial:
How to use string formatters in Python 3

I can recommend this method of formatting as being a powerful way of formatting numbers and inserting variable values into strings.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.