Python formatting update - including named completions
Archive - Originally posted on "The Horse's Mouth" - 2015-12-10 02:31:01 - Graham EllisAs from Python 2.6, a format method has been introduced in addtion to the % operator on strings to provide a more flexible and improved way of convering objects (of various type) into strings. Select [here] to open the source in a new window which was used to get this result:
munchkin:cambx grahamellis$ python3 earlier
How all are ya (in metres) 1.76
How heavy are ya (in kgs) 74
Your bmi is 23.889 if so
Your bmi is 000023.889 if so
Your bmi is 23.889 if so
Your bmi is 23.889 if so
Your bmi is 23.889 if so
Your bmi is 23.889 if so
Your bmi is 23.889462809917354 if so
for height 1.76 and weight 74.0 the bmi is 23.889
for height 1.76 and weight 74.0 the bmi is 23.889
for height 1.76 and weight 74.0 the bmi is 23.889
munchkin:cambx grahamellis$
This new format method on a string is what we recommend you use in Python 3 ... it has a much inreased flexibility, and indeed allows you to write much cleaner code too - for example by filling in format elements by name:
print ("Your bmi is {result} if so".format(result=bmi))
or indeed
result = {"height":h, "weight":w, "bmi":bmi}
print ("for height {height} and weight {weight} the bmi is {bmi:10.3f}".format(**result))