Formatting Method, Function and f-string Compared

There is an old rule in Python that there should be only one way to do something but over the last few years the process of formatting has spawned several. The oldest is “Interpolation”. It is buggy, obsolete, being deprecated, and using it is just asking for trouble. In the next version of Big Daddy’s Formatting Option Toolbox it will be consigned to the dust bin of history.

So much for interpolation.

The format function and the string format method are both pretty widely used and despite what some seem to think, they are NOT mutually exclusive. f-strings are new in version 3.6 and some Pythonistas think f-strings were the last rung of the ladder that put Python in direct competition with every other language ever. I’ll leave that debate for another time.

Meanwhile here is a short interesting test. What follow are three ways to format the same sentence. The first uses the string format method only. The second uses f-strings. The third uses the string format method combined with the format function. (The format function by itself has no substituion ability.) All three employ the mini-language format spec, so if you haven’t done so already, now is the time to learn it. All three result in:
“Bob estimated pi to be 3.14159.”

The timing results (10000 reps) were:
# string format METHOD only – time: 0.010211300000000034
# string format method plus use FUNCTION to format number – time: 0.015578599999999998
# f-string – time: 0.007280400000000076

Timeit is fun and addictive if you are a geek concerned about execution speeds of a small code sample. Here is the code:

# Timing the format function, function + method and f-string
import timeit
'''
# here is what we are testing, one at a time, using the timeit module
name = "Bob"
pi =  3.14159265358979323846
# string format METHOD only
print("{} estimated pi to be {:.5f}.".format(name, pi))
# string format method plus use FUNCTION to format number
print("{} estimated pi to be {}.".format(name, format(pi, ".5f")))
# f-string
print(f"{name} estimated pi to be {pi:.5f}.")
#  ---------------------------------------------------
'''
mysetup = "name, pi = 'Bob', 3.14159265358979323846"
mycode =''' 
formatted_string = (f"{name} estimated pi to be {pi:.5f}.")
'''
print (timeit.timeit(setup = mysetup, stmt = mycode, number = 10000))