Main Content

Formatting output in Python through str.format

Archive - Originally posted on "The Horse's Mouth" - 2011-07-07 05:10:07 - Graham Ellis

Python's str.format method provides functionallity to convert values into string representations - typically for output. Taking (for example) the resukt or dividing 1 by 7 - a recurring decimal - and rounding and truncating in to 2 decimal places if it's a price ...

  value = 1.0 / 7.0
  print (value) ; # control
  print ("{0:.2f}".format(value))


And that runs as follows:

  wizard:cruise graham$ python3 pymf2
  0.142857142857
  0.14
  wizard:cruise graham$


You can pass multiple values into the format method - by position number, or by name, and use the {} notation within the string to fill in values. With just a single alphanumeric value in a pair of {}es, a default format is used, but with various special characters and modifiers you can also select field width, justification, padding and more - as I've started to show in the example above. There's a complete worked example [here] on our web site - part of the resources that we use in teaching our Python courses.