Printing and f-strings
We’ve encountered the print function a few times in this Session and its easy to use - you provide some variables or values and it prints them to the screen. However, we can use f-strings to format the appearance of the information we’re printing so that it looks a little bit neater than the default.
To see how and why, lets return to our first exercise on the Haber-Bosch process. Written as a single block, our code was
p_N2 = 1.00
p_H2 = 3.00
p_NH3 = 3.82e-2
K = p_NH3 ** 2 / (p_N2 * p_H2 ** 3)
delta_G = -scipy.constants.R * temperature * math.log(K)
delta_G /= 1000
print(delta_G)24.345175281081325
The code works and we get the right answer, but we’ve got far too many significant figures, and we haven’t written any units - our presentation is bad.
To tidy this up, we can use an f-string when we print. An f-string lets you lay out how numbers, strings, and even booleans will be printed to the screen.
Here’s a basic example
score = 10
print(f'I give CH12004 a {score}/10!')I give CH12004 a 10/10
The f-string is defined by the use of f just before the first quotation mark, and the subsequent use of braces (curly brackets) into which we can put the name of the variable we want to print.
Let’s now apply this to the Haber-Bosch exercise
print(f'delta_G = {delta_G} kJ mol^-1')delta_G = 24.345175281081325 kJ mol^-1
That’s a little bit better, but we’ve still got too many numbers! We can use more advanced features of f-strings to format the number of decimal places - let’s imagine we want the number to two decimal places.
print(f'delta_G = {delta_G:.2f} kJ mol^-1')delta_G = 24.35 kJ mol^-1
or the number of significant figures using
print(f'delta_G = {delta_G:.3g} kJ mol^-1')delta_G = 24.4 kJ mol^-1
That’s much better! Here we’ve used a format specifier to tell Python that delta_G is float which we want to represent with either
- A string with two decimal places using the
:.2fspecifier. - A string with three significant figures using the
:.3gspecifier.
In both cases Python has done the “rounding” for us.
Always use f-strings and format specifiers when you want to show data to a certain number of decimal places (or significant figures). Never use a rounding function - these are prone to errors and is unneccessary.
There are different format specifiers for different types, and lots of ways of manipulating information using identifiers.
The definitions of all possible format specifiers are here - this might take a few minutes to get your head around, but remembering {:Nf} and {:Ng} for decimal place and significant figure specification will get you a long way!
We can go one step further and use some unicode characters to make this the perfect print statement.
print(f'ΔG = {delta_G:.3g} kJ mol⁻¹')ΔG = 24.4 kJ mol⁻¹