devnotes.

f-strings and String Formatting

f-strings (formatted string literals, Python 3.6+) are the modern, preferred way to build strings that embed variable values — clearer and faster than the older %-formatting or .format() styles.

name = "Rahim"
age = 25
price = 19.999

print(f"Hello, {name}! You are {age} years old.")   # embeds variables directly
print(f"Price: ${price:.2f}")                          # "Price: $20.00" — 2 decimal places
print(f"{age = }")                                      # Python 3.8+: "age = 25", great for debugging
print(f"{name.upper()}")                                # expressions work inside {}

# Older styles (still seen in existing code, avoid for new code):
print("Hello, %s!" % name)              # % formatting — legacy
print("Hello, {}!".format(name))          # .format() — pre-f-string standard

Anything inside an f-string's {} is evaluated as a real Python expression — variables, function calls, arithmetic, even method calls ({name.upper()}) — not just simple substitution. The : inside the braces introduces a format spec, controlling things like decimal places (:.2f), padding, alignment, and thousands separators (:,) — f"{1234567:,}" produces "1,234,567".

The {age = } debugging syntax (Python 3.8+) is a small but genuinely useful trick: it prints both the expression's source text and its value, saving you from writing print(f"age = {age}") by hand and keeping the label in sync if the variable is ever renamed. f-strings should be the default for all new string formatting — reach for %-style or .format() only when reading legacy code that already uses them.

f-strings and String Formatting in Python | DevNotes