Skip to content

Mastering Text Formatting with f-strings

Programming Python Difficulty 1/5

Beginning of the lesson

Mastering Text Formatting with f-strings

Turn plain values into clean, tidy, professional-looking text

Big Idea: An f-string lets you drop values, and even little calculations, straight into a piece of text. Add a small format spec after a colon and Python will line things up, round numbers, add commas, and show percentages for you automatically.
By the end you will be able to:
  • build an f-string with the f prefix 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers