Formatting output - why we need to, and first Python example
Archive - Originally posted on "The Horse's Mouth" - 2012-10-09 08:37:46 - Graham Ellis
I understand that if you win the lottery in a big way, a lot of long lost relatives who have fallen on hard times will come out of the woodwork ... and if you've got a lot of brothers and sisters you might find a surprising number of nieces and nephews!
Being a generous soul, you've decided to split £100,000 of your winnings equally among them all - that's all 17 of them - giving each of them £5882.35 .
That's part of an exercise we do early on during many of our Python courses such as Python Programming which started yesterday. The demonstration lets me show you how working with whole numbers (integers) gives the result 5882, and working with decimals (a.k.a. floats or reals) gives the result 5882.35294117647
Of course, what I really want to print out is "5882.35". Now the detail of that comes with string formatting and string handling - not on the first day of the course - but I do (and will) give delegates a taster to show that "yes, it can be easily done". The example code - using the % operator that has always been available since I started with Python, and the string.format method introduced in Python 2.6, enhanced in 2.7 and the way for the future in Python 3 - is [here].
Results?
munchkin:opy grahamellis$ python trimmer
With 17 in favour, each gets 5882.35294118
With 17 in favour, each gets 5882.35
With 17 in favour, each gets 5882.35
With 17 in favour, each gets 5882.35
With 17 in favour, each gets 5882.35
munchkin:opy grahamellis$