f-string

Clean and efficient string formatting

Since Python 3.6, you can use f-strings to format strings. In addition to being faster than %-formatting and str.format(), the code becomes also way more readable.

Time comparisons

f-string

%%timeit
f"Hello, I'm {first_name} {last_name} and I'm {age} years old."
#132 ns ± 0.422 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

str.format()

%%timeit
"Hello, I'm {} {} and I'm {} years old.".format(first_name, last_name, age)
#254 ns ± 1.46 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%-formatting

%%timeit
"Hello, I'm %s %s and I'm %s years old." % (first_name, last_name, age)
#219 ns ± 0.762 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Examples

Limit the number of digits

accuracy = .97334345457
print(f"Accuracy: {accuracy:.4f}")

>>> Accuracy: 0.9733

Use operations inside brackets

accuracy = .97334345457
print(f"Accuracy: {accuracy*100:.2f}%") 

>>> Accuracy: 97.33%

Scientific notation

n_iter = 100000
print(f"Number of iterations: {n_iter:.2e}%")

>>> Number of iterations: 1.00e+05

Documentation

https://docs.python.org/3/reference/lexical_analysis.html#f-strings