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
fin front, likef"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":
- Python sees the
fand looks for holes. {name}is replaced by the value inname, Rimi.{age}is replaced by 12, turned into text automatically.- 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)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))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}"givesNameError: name 'nmae' is not defined, just like anywhere else. - A number format on text. If
price = "3.5"(a string),f"{price:.2f}"givesValueError: Unknown format code 'f' for object of type 'str'. - Wanting real braces. Double them:
f"{{x}}"shows{x}.
name = "Rimi"
print("Hi {name}")Quiz
What does this print?
x = 3 print(f"x is {x}")What does this print?
print(f"{2 * 5}")What does this print?
n = "sam" print(f"Hi {n.upper()}")What does this print?
v = 2.5 print(f"{v:.2f}")This should print "Hello Tom". Which line is wrong?
name = "Tom" print("Hello {name}") print("Bye")What does this print?
score = 7 print(f"{score=}") print("{}/{}".format(score, 10))
Coding tasks
itemandcostare given. PrintA book costs 250 takausing an f-string.wis 7 andhis 3. PrintArea: 21, working out the area inside the braces.totalholds 1234.5. PrintPay 1234.50, always with two decimal places.