Formatting Strings - Lakelands Computing

Title
Go to content
Formatting Strings
To make a string print the way you want it to you can format it using the format() function. It is best explained through example:

  • price = 12
  • text = "The price is {} pounds"
  • print(text)

The third line print(txt) would just print it out (try it in the trinket), but if we change the second line, putting some formatting inside the {}, and and the .format() it will print out correctly - with a decimal point and 2 digits to the right of the decimal - 12.00

  • price = 12
  • text = "The price is {:.2f} pounds"
  • print (text.format(price))

The formatting I find most useful is the :.2f  shown to control the number of decimal points and the :, to put a comma in for thousands. There is a list of common formatting on this w3schools page
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content