LESSON 05 · BEGINNER PATH8 min

String Formatting

Build readable text that includes variables and formatted numbers.

Video coming to YouTube

Work through the full lesson and run its code while the video is being prepared for publication.

Understand the concept

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.

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.

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.