I agree that formatting is mainly used for readability, but since the release of f-rows in 3.6 tables have turned in terms of performance. I also think that f-lines are more readable / supported, since 1) they can be read left-right, as in most ordinary texts, and 2) the concatenation disadvantages associated with the interval are eliminated, since the variables are built-in.
Running this code:
from timeit import timeit runs = 1000000 def print_results(time, start_string): print(f'{start_string}\n' f'Total: {time:.4f}s\n' f'Avg: {(time/runs)*1000000000:.4f}ns\n') t1 = timeit('"%s, %s" % (greeting, loc)', setup='greeting="hello";loc="world"', number=runs) t2 = timeit('f"{greeting}, {loc}"', setup='greeting="hello";loc="world"', number=runs) t3 = timeit('greeting + ", " + loc', setup='greeting="hello";loc="world"', number=runs) t4 = timeit('"{}, {}".format(greeting, loc)', setup='greeting="hello";loc="world"', number=runs) print_results(t1, '% replacement') print_results(t2, 'f strings') print_results(t3, 'concatenation') print_results(t4, '.format method')
gives this result on my machine:
% replacement Total: 0.3044s Avg: 304.3638ns f strings Total: 0.0991s Avg: 99.0777ns concatenation Total: 0.1252s Avg: 125.2442ns .format method Total: 0.3483s Avg: 348.2690ns
A similar answer to another question is given on this answer .
source share