F-Strings

F-Strings

An f-string builds a string from a template. It is written with an f before the opening quote. Inside it, anything between curly braces is evaluated and inserted into the string:

name = "Parsnip"
age = 36
sentence = f"{name} is {age} years old."
print(sentence)

Output:

Parsnip is 36 years old.

Unlike concatenation with +, an f-string accepts numbers directly — no conversion, no manual spaces.

The braces can hold any expression, not only a variable name:

price = 12.5
print(f"Two tickets cost {price * 2} dollars.")

Output:

Two tickets cost 25.0 dollars.

Exercise

The starter code creates item, quantity, and price.

  1. Create order using an f-string, so that it holds exactly:

3 x notebook at 4.5 each

Use all three variables inside the braces — do not type the values into the string. 2. Print order.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestFStrings(unittest.TestCase):
    def test_order_has_the_exact_text(self):
        self.assertEqual(order, "3 x notebook at 4.5 each")

    def test_item_is_unchanged(self):
        self.assertEqual(item, "notebook")

    def test_quantity_is_unchanged(self):
        self.assertEqual(quantity, 3)
item = "notebook"
quantity = 3
price = 4.5

order = f"{quantity} x {item} at {price} each"
print(order)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.