LESSON 05 · BEGINNER PATH12 min

String Formatting

An f-string places a value inside a string when you write an f before the opening quote. Curly braces mark each expression to evaluate. This is useful for labels, messages, and summaries.

Build readable text that includes variables and formatted numbers.

Before you start: Variables and Types

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: String Formatting

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    A program becomes much more useful when it can explain its results in a sentence. Imagine a lesson dashboard that knows a learner's name, how many lessons they completed, and their latest quiz score. You could type a separate message for every learner, but that would be slow and easy to get wrong. A formatted string combines fixed words with the current values of variables. In Python, an f-string is a readable way to build that message. Open the String Formatting lesson and find the starter values for student, completed, and score. Before you press Run, predict two output lines. What name and count will appear in the first sentence?

  2. 00:40

    How many digits after the decimal point will the score display? We will also see that an f-string can contain a calculation, that its value is created at a particular moment, and that formatting changes display without changing the stored number. The letter f immediately before the opening quote tells Python to evaluate expressions inside curly braces. In the first print call, the student placeholder becomes Maya and the completed placeholder becomes three. Python joins those values with the surrounding words and punctuation. You can put a short expression inside braces too, such as two plus three, and the result five will appear.

  3. 01:21

    The second print call uses a format specifier after the score: colon, dot, two, f. It requests two digits after the decimal point. With a score of eight point seven five, the output displays eight point seven five. If the score were seven point five, the output would include a trailing zero. This is display formatting; the variable still holds a numeric value that you can calculate with. Now examine the first deeper example. We create a message while name is Ava, then change name to Kai. Printing the saved message still greets Ava, because the f-string was evaluated when that message was created. A new f-string built afterward greets Kai.

  4. 02:03

    This is an important distinction when a value changes during a program. The second guide example places a calculation inside the placeholder. Three notebooks at six dollars each cost eighteen dollars. The expression price times quantity is evaluated before the surrounding sentence is printed. Compare that with printing a hard-coded total: if the quantity changed, the calculated message would update correctly. The third guide example formats a large budget with a comma as a thousands separator and a ratio as a percentage. Twelve thousand appears with a comma, and the ratio zero point three seven five appears as thirty-seven point five percent when formatted to one decimal place.

  5. 02:48

    Printing ratio again still shows its original numeric value. The comma and percent sign describe how a reader sees the value; they do not rewrite the data. This is also why you should keep numeric data numeric until it is time to present it. If you turn a number into a formatted string too early, later arithmetic becomes awkward or fails. A good sequence is calculate with numbers first, then format the final result for a person. Try changing the quantity in the notebook example from three to four. Before running, predict a cost of twenty-four dollars. The code should compute the new total without editing the message template.

  6. 03:29

    When designing output, ask what information a person needs. Labels, units, punctuation, and a suitable number of decimal places make a calculation much easier to understand. Let us make two typical mistakes. First, remove the f before the opening quote and run the code. The braces and placeholder names now appear literally in the output. Python has treated the entire line as an ordinary string; it has not tried to insert values. Put the f back and confirm that the placeholders are replaced. Next, change a placeholder to a variable name that does not exist. Python raises NameError because the expression inside the braces is evaluated like any other Python expression.

  7. 04:16

    Check spelling and capitalization against the assignment above it. If a formatted number looks wrong but the program still runs, inspect the format specifier and the original numeric value separately. Fixing the precise cause is better than rewriting the whole message and losing the parts that already worked. There is a third quick check: every opening brace that starts a placeholder needs a closing brace. If you leave one out, the string is not well formed and Python reports a syntax problem before the program runs. Look at the exact highlighted line and pair the braces. You can then test with a very small f-string containing only one placeholder, confirm it works, and add the rest of the message.

  8. 05:01

    Now complete the practical task. Create a variable named topic with the string loops. Use an f-string that inserts topic into a sentence saying Maya is studying loops. The checker looks for both the exact topic value and an actual f-string used to print the sentence. Simply typing the finished sentence as fixed text may look right on screen, but it would not respond if topic changed. Predict the output, run your program, and compare it character by character with the requested sentence. If you see braces in the output, check the f prefix. If you see NameError, check the variable name. Then change topic to functions temporarily and observe how the sentence responds, before returning to loops for the task checker.

  9. 05:48

    The quiz asks what an arithmetic expression inside braces produces, what happens when f is missing, and how to ask for two decimal places. Give the rule before selecting an answer. The larger lesson is to separate data from the words that describe it. The variable stores the changing fact; the f-string turns that fact into an understandable message. In the next lesson, we will inspect and transform the characters inside those strings.

Understand the concept

A format specifier inside the braces can control display. For example, :.2f shows a floating-point value with two digits after the decimal point.

  • Prefix a string with f
  • Use {expression} placeholders
  • Format decimals with :.2f

See it step by step

Read the code, predict the output, then compare it with the result.

01. Insert two values

PYTHON
student = "Ava"
topic = "lists"
print(f"{student} is studying {topic}.")
EXPECTED OUTPUT
Ava is studying lists.

The f before the string tells Python to replace each {name} with its current value.

02. Format a decimal

PYTHON
score = 7.5
print(f"Score: {score:.2f}")
print(f"Next lesson: {2 + 1}")
EXPECTED OUTPUT
Score: 7.50
Next lesson: 3

The :.2f format displays two decimal places; an f-string can also evaluate an expression.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

An f-string captures values when it is created

An f-string evaluates its braces at the moment that expression runs. If you save the finished message and then change a variable, the old message does not update automatically. This is useful when you want a record of what was true at a particular moment, such as a receipt or a log line.

The first message below was built while name was Ava. A new f-string after reassignment uses Kai. Predict both lines before running the program, then move the first assignment below the name change. This shows why a message template and the final string value are different ideas.

PYTHON
name = "Ava"
message = f"Hello, {name}"
name = "Kai"
print(message)
print(f"Hello, {name}")
EXPECTED OUTPUT
Hello, Ava
Hello, Kai
Follow the reasoning
  1. The first f-string turns the current name into a finished string.
  2. Changing name later does not rewrite message.
  3. The second f-string reads the new value.
02 / 03

Build a sentence from calculated values

The braces of an f-string can hold an expression, not only a variable name. That lets a report show a calculated value without first creating a separate name for every intermediate result. Keep the expression short, though: a long formula inside a sentence is harder to inspect and harder to reuse elsewhere.

In this checkout example, the total depends on both price and quantity. The text labels give the number context for a reader. Predict the total before running it, then change quantity to 4 and see whether the text and calculation remain in agreement. If the formula grows, calculate total on its own line and interpolate that name.

PYTHON
item = "notebook"
price = 6
quantity = 3
print(f"{quantity} {item}s cost ${price * quantity}.")
EXPECTED OUTPUT
3 notebooks cost $18.
Follow the reasoning
  1. The names item and quantity supply words and a count.
  2. price * quantity is evaluated inside the braces.
  3. Only the resulting number 18 appears in the finished string.
03 / 03

Format for a reader without changing the data

A format specifier changes how a value is displayed, not the underlying number. A comma can group thousands and a percent format multiplies a ratio by 100 for display while adding the percent sign. These choices make reports easier to scan, but your calculations should still use the original numeric values.

The example prints a budget and a completion ratio in familiar notation. Afterward it prints the original ratio to show that formatting did not turn 0.375 into 37.5 in memory. Try changing the ratio to 0.5 and predict the displayed percentage. A label should always explain what the number measures.

PYTHON
budget = 12000
ratio = 0.375
print(f"Budget: ${budget:,}")
print(f"Complete: {ratio:.1%}")
print(ratio)
EXPECTED OUTPUT
Budget: $12,000
Complete: 37.5%
0.375
Follow the reasoning
  1. :, adds a thousands separator for display.
  2. :.1% displays the ratio as a percentage with one decimal place.
  3. The final print confirms that ratio is still 0.375.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnCreate a variable called topic with the value "loops". Print "Maya is studying loops." using an f-string.
Need a hint?

Set topic = 'loops'. In an f-string, put {student} and {topic} inside braces, and include the exact punctuation at the end.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.What does print(f"{2 + 3}") display?

    02.What does print("{name}") display when the f prefix is missing?

    03.Which specifier displays 3.14159 with two decimal places?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Missing f prefix

    COMMON MISTAKE
    name = "Maya"
    print("Hi, {name}")
    FIX
    name = "Maya"
    print(f"Hi, {name}")

    What happens: The literal text Hi, {name} is displayed.
    Add f before the opening quote to evaluate placeholders.

    Unknown placeholder

    COMMON MISTAKE
    name = "Maya"
    print(f"Hi, {username}")
    FIX
    name = "Maya"
    print(f"Hi, {name}")

    What happens: NameError because username has not been defined.
    A placeholder must refer to a defined name or valid expression.

    Browse this lesson’s problem fixes