f-strings often replace
.format() in everyday code, but their capabilities are not always fully utilized. They support formatting, function calls, working with data structures, and convenient debugging (from 3.8+).f-strings are convenient for aligning columns without additional tools. This makes the output readable in the CLI and logs:
rows = [
("id", "name", "role"),
(1, "Ivan", "admin"),
(2, "Olga", "editor"),
]
for r in rows:
print(f"{r[0]:<5} {r[1]:<10} {r[2]:<10}")
Debug expressions (Python 3.8+):
{x=> displays the name and value of the variable, which speeds up debugging. Supports formatting of calculations:x = 12
y = 7
print(f"{x=} {y=} {x*y=} x/y={x/y:.3f}")
Specifiers
!r, !a: !r - repr(), !a - ascii() for unambiguous logs. Eliminates ambiguities in the output of objects:path = "/var/data/config.yaml"
print(f"{path!r} {path!a}") # repr and ascii()
Specifiers support width and padding, for example 08d for zeros. This is convenient for reports and IDs:
n = 42
print(f"{n:08d}") # → #00000042
You can access dictionaries and immediately calculate metrics, for example
len():data = {"user": "Ivan", "items": [1, 2, 3]}
print(f"{data['user']}=», items={data['items']}")
print(f"len(data['items'])={len(data['items'])}")🔥 f-strings are a cool tool for formatting, logging, and debugging, if you apply them taking into account the version of Python and the context of the output.
🚪 @DataScience4