Python 3D Academyবাংলা

f-strings: filling in templates

🌍 In real life. An exam admit card is printed from one template: "Name: ____, Roll: ____, Centre: ____". For each student, the blanks are filled with that student's details. Nobody writes each card from scratch.

An f-string is a template like that for your output.

The idea in one sentence: put f before a string's opening quote, and Python fills each { } hole with the value of whatever is inside it.

Its words:

  • f-string: a string with f in front, like f"Hi {name}"
  • hole (placeholder): a pair of braces { } with a name or expression inside
  • format spec: an instruction after a colon in the hole, like {price:.2f}

Step by step, for f"{name} is {age} years old":

  1. Python sees the f and looks for holes.
  2. {name} is replaced by the value in name, Rimi.
  3. {age} is replaced by 12, turned into text automatically.
  4. The finished string is Rimi is 12 years old.
name = "Rimi"
age = 12
print(f"{name} is {age} years old")

Why not just use +? Joining text and values with + gets messy, needs spaces in the right places, and can't join a str and an int at all. An f-string turns each value into text for you:

age = 12
print("I am " + age)
TypeError: + can join two strings, but age is an int.

Anything can go inside the braces, even maths or a method call:

a = 7
b = 5
print(f"{a} + {b} = {a + b}")
city = "dhaka"
print(f"Welcome to {city.title()}!")

Add a colon inside the braces to format a number: {price:.2f} shows exactly 2 decimal places, and {n:,} puts commas between the thousands.

price = 3.5
print(f"Total: {price:.2f} taka")
population = 170000000
print(f"{population:,} people")
pi = 3.14159
print(f"{pi:.1f}")

Debugging with =. Put = at the end of a hole and the f-string shows the expression as well as its value: f"{total=}" gives total=14.0. It is the quickest debugging print there is (Lesson 7.7).

Older ways you'll still meet. Before f-strings arrived in Python 3.6, people wrote "{} is {}".format(name, age): the .format() method fills the {} holes in order, and it takes the same format specs, like "{:.2f}".format(price). Even older code uses %: in "%s is %d" % (name, age), %s is a hole for any value and %d one for a whole number. You don't need to write them, but you will read them in other people's code.

name = "Rimi"
age = 12
total = 3.5 * 4
print(f"{total=}")
print(f"{age + 1=}")
print("{} is {}".format(name, age))
print("{:.2f} taka".format(total))
print("%s is %d" % (name, age))
The last three lines print the same kind of thing three ways. In new code, use the f-string.

Mistakes and edge cases.

  • Forgetting the f. Then Python prints the braces just as they are. It's one of the most common mistakes (see below).
  • A misspelt name in a hole. f"{nmae}" gives NameError: name 'nmae' is not defined, just like anywhere else.
  • A number format on text. If price = "3.5" (a string), f"{price:.2f}" gives ValueError: Unknown format code 'f' for object of type 'str'.
  • Wanting real braces. Double them: f"{{x}}" shows {x}.
name = "Rimi"
print("Hi {name}")

Quiz

  1. What does this print?

    x = 3
    print(f"x is {x}")
  2. What does this print?

    print(f"{2 * 5}")
  3. What does this print?

    n = "sam"
    print(f"Hi {n.upper()}")
  4. What does this print?

    v = 2.5
    print(f"{v:.2f}")
  5. This should print "Hello Tom". Which line is wrong?

    name = "Tom"
    print("Hello {name}")
    print("Bye")
  6. What does this print?

    score = 7
    print(f"{score=}")
    print("{}/{}".format(score, 10))

Coding tasks

  1. item and cost are given. Print A book costs 250 taka using an f-string.

  2. w is 7 and h is 3. Print Area: 21, working out the area inside the braces.

  3. total holds 1234.5. Print Pay 1234.50, always with two decimal places.