Lesson 10 of 18 · 2 min
f-strings — The Best Way to Mix Variables and Text
The WHY — Why Not Just Use + to Join Strings?
Joining strings with + is messy, error-prone, and requires converting every number to string first:
name = "Priya"
age = 20
# OLD WAY — ugly and requires str() conversion
print("My name is " + name + " and I am " + str(age) + " years old.")
f-strings solve all these problems:
name = "Priya" # student name
age = 20 # student age
gpa = 3.75 # student GPA
# Put f before the opening quote, use {} to embed variables
print(f"My name is {name} and I am {age} years old.") # embed variables
print(f"My GPA is {gpa:.2f}") # .2f = 2 decimal places
print(f"Next year I will be {age + 1}.") # math inside {}
Output: My name is Priya and I am 20 years old. My GPA is 3.75 Next year I will be 21.
f-string Formatting Options
pi = 3.14159265 # value of pi with many decimals
big_num = 1234567.89 # a large number
score = 0.1874 # a decimal between 0 and 1
print(f"Pi: {pi:.2f}") # round to 2 decimal places
print(f"Pi: {pi:.4f}") # round to 4 decimal places
print(f"Number: {big_num:,.2f}") # add thousands comma separator
print(f"Score: {score:.1%}") # multiply by 100 and show as percentage
print(f"Name: {'ahmed'.upper()}") # call methods inside {}
Output: Pi: 3.14 Pi: 3.1416 Number: 1,234,567.89 Score: 18.7% Name: AHMED
