Skip to content
Tactiverge

Python reference

Strings and f-strings

Also called: formatted string · f"{x:.2f}" · string formatting · str

Definition

An f-string, written f"…", replaces each {expression} inside it with that expression's value, optionally formatted, as in {voltage:.2f} for two decimal places.

Picture it

f-strings are the fastest way to print readings with units and a sensible number of decimals. Format specs after the colon control width, precision and style: .3g for three significant figures, .1% for percentages, 08b for an 8-bit binary number.

Worked example

What does f"{3.14159:.2f} V, {0.256:.1%}, {5:08b}" produce?

  1. .2f → 3.14
  2. .1% multiplies by 100 → 25.6%
  3. 08b → binary padded to 8 digits → 00000101

Answer"3.14 V, 25.6%, 00000101".

✓ The 3 numbers in this answer are recomputed from scratch by an automated test.

In Python

v = 3.14159
print(f"Battery: {v:.2f} V")   # Battery: 3.14 V
print(f"{v=}")                  # v=3.14159 (debug form)

Common misconceptions

  • Misconception: Strings are immutable: s.upper() returns a new string, it does not change s.
  • Misconception: "5" + 3 is an error; convert with int("5") or str(3) first.