Sponsored Reserved space — layout preview until AdSense is connected
Python f-strings — formatting numbers and text cleanly

Tutorial

Python f-strings — formatting numbers and text cleanly

Master f-string interpolation, thousands separators, fixed decimals, and why they beat old %-style formatting for everyday code.

March 2026 · 6 min read · 13 views · 0 hearts

What is an f-string?

Since Python 3.6, f-strings (f"...") let you interpolate variables and expressions directly inside a string. They are usually the clearest choice for formatting user-visible text.

Interpolation

Variables inside curly braces are evaluated when the string is created:

user = "sam"
points = 42
msg = f"{user} scored {points} points today."
print(msg)

Number formatting

After an expression, add a colon and a format specifier. Common patterns include grouping thousands, fixed decimal places, and zero-padding.

population = 8_021_000_000
print(f"Rough population: {population:,}")

ratio = 22 / 7
print(f"Pi-ish: {ratio:.4f}")

Debugging helpers

Python 3.8+ supports f"{expr=}" which prints both the expression text and its value — handy while iterating locally.

limit = 25
print(f"{limit=}")

Compared to older styles

  • str.format is still fine for templates or translated strings.
  • % formatting exists mainly in legacy code.
  • For everyday diagnostics and logs, f-strings tend to win on readability.

Try it yourself

Open the IDE sample linked above — tweak names, precision, and grouping — then extend the snippet with your own variables.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

3 in thread

Join the discussion

Shown next to your comment.

Constructive tone · up to 4,000 characters
  1. Fapebac202 Member
    Lol
    Reply

    Replies

    Fapebac202 Member
    Is this is even working well? 😀😀
    Fapebac202 Member
    THATS COOL

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected