Python F-Strings: Format Values and Decimal Places
Core idea
An f-string is a string literal with the prefix f before its opening quote. Place a Python expression inside braces to insert its value. A colon inside a replacement field introduces a format specification. For example, .2f displays a number in fixed-point notation with two fractional digits.
item = "tea"count = 3print(f"{item}: {count * 2} packs")Python evaluates the multiplication inside braces before constructing the resulting string. The other characters are literal text.
Format decimal display
length = 1.375print(f"Length: {length:.2f}")print(length)The displayed string uses two decimal digits, while the original numeric value is unchanged. Formatting follows float rounding behavior; it is not an exact decimal accounting policy.
Print literal braces
Double braces in an f-string produce literal braces. Without the f prefix, ordinary braces remain text.
Common mistake
f"{amount:.2f}" creates text, not a float. Use it for display; keep the numeric value for further arithmetic. Do not put an f-string containing untrusted input into a code evaluator.
Practice
Use distance = 2.5 and format the message Distance: 2.50 km. Then print the original distance to see that its value has not changed. Next chapter: Boolean logic and decisions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
F-string formatting
Check your understanding of f-string formatting.
What is printed?
print(f"Total: {3 * 4}")What is printed?
print(f"{2.5:.2f}")What is printed?
x = 3print(f"{{x}} {x}")Does formatting a float into an f-string change its original numeric value?