Mastering Text Formatting with f-strings
Turn plain values into clean, tidy, professional-looking text
- build an f-string with the
fprefix and{ }placeholders, - put a variable or a small calculation inside a placeholder,
- round a number to a set number of decimals with
:.2f, - line text up left, right, or center with
:<,:>,:^and a width, - add thousands commas with
:,and show percentages with:%, - use the handy debug shortcut
{value=}.
1. What is an f-string?
You already know how to make text (a string) from the earlier lesson Working with Text. An f-string is a string with a tiny letter f written right before the opening quote. That little f gives the string a superpower: anything you put inside curly braces { } is treated as Python code, run, and dropped into the text.
name = "Sara"
age = 12
print(f"Hi {name}, you are {age} years old.")
Output:
Hi Sara, you are 12 years old.
Without the f, Python would print the words {name} and {age} exactly as written, braces and all. The f is what tells Python "look inside the braces and fill them in".
Analogy: think of an f-string as a fill-in-the-blank sentence, like a party invitation that says "Dear ____, the party is at ____ o'clock." The braces are the blanks, and Python fills each blank with the value you named.
2. Putting expressions inside the braces
The braces do not only hold plain variables. You can put a small expression inside them, and Python works out the answer first, then shows it.
price = 3
count = 4
print(f"That costs {price * count} coins.")
print(f"Next year you will be {age + 1}.")
Output:
That costs 12 coins.
Next year you will be 13.
Here price * count is calculated to 12 before it is placed in the text. You can call functions inside braces too, for example {name.upper()} would show SARA. Keep the code inside braces short and simple so your sentence stays easy to read.