Python string formatting embeds variables and formatted numbers inside text templates cleanly. Since Python 3.6, f-strings (f"...") are the fastest, clearest way to format strings without counting positional placeholders.
Inside an f-string, place a colon : after any expression to control decimals, commas, alignment, or percentages in one compact specifier.
You can format currency with two decimal places and thousands separators, turn ratios into percentages, and pad table columns cleanly.
product = "SSD 1TB"
price = 1249.5
margin = 0.184
units = 7
print(f"{product:<12} | ${price:,.2f} | Margin: {margin:.1%}")
print(f"Batch #{units:04d}") # Batch #0007
In Python 3.8+, adding = after a variable name prints both the expression and its value for quick debugging: print(f"{price=}, {units=}").
.format() Still HelpsF-strings evaluate immediately where you write them. If you load a reusable template string from a configuration file or translation table, store "Hello, {name}!" and call template.format(name=user) later.
% formatting in new code: "%s: %d" % (a, b) fails awkwardly if you pass a tuple value and is harder to read than f-strings..format(): Never let users control the template passed to .format(), because format strings can inspect object attributes.{{ and }} for literal braces: Inside an f-string, double curly braces {{ and }} output literal { and } characters.+ concatenation or .format()?Yes. CPython compiles f-strings directly into optimized bytecode instructions, making them faster than both .format() and % formatting.
{...}?Yes. Any valid Python expression works inside braces, such as f"Total: {qty * unit_price:.2f}".
Python 3.12 lifted earlier parser limits, allowing quotes matching the outer f-string, comments, and backslashes inside {...} expressions.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.