f-string — Modern String Formatting (PEP 498)
f-string — Modern String Formatting (PEP 498)
🎯 After reading this lesson
After finishing this lesson, you will be able to confidently do the following 3 things.
- ▸✅ f-string basics + expressions + format specs
- ▸✅ f'{var=}' debug expression (Python 3.8+)
- ▸✅ Why f-string is preferred over % / .format()
Keep the learning goals as a checklist, and close the lesson once you can answer all of them.
f-string — Code + Output
f"..." = embedding variables into a string. Standard since Python 3.6+. Fastest and most concise.
1. Basics
2. Comparison with older styles
# ✅ f-string (3.6+) — shorter and faster
f"{name} is {age} years old"
pythonpi = 3.14159265
print(f"{pi:.2f}") # 3.14 (2 decimal places)
print(f"{pi:.4f}") # 3.1416
print(f"{1234567:,}") # 1,234,567 (thousands comma)
print(f"{0.85:.0%}") # 85% (percentage)
print(f"{42:>5}") # " 42" (right-aligned 5 chars)
print(f"{42:0>5}") # "00042" (0 padding)
pythonx = 10
y = 20
print(f"{x=}, {y=}, {x+y=}") # x=10, y=20, x+y=30
# variable name + value at once — the ultimate debugging trick
pythonmessage = f"""
Hello {name}
Age: {age} years old
"""
# quote escaping
print(f'He said: "Hello"') # OK
print(f"Name is \"{name}\" ") # Name is "Hong Gil-dong"
```
One-line summary
The only standard in Python 3.6+. % and .format() are legacy.
🐍 Try it yourself — f-string — Run it directly
🤖 Try asking AI like this
Knowing the concepts in this lesson lets you give AI specific instructions — not a vague 'fix this', but a request with vocabulary. That is the starting point for saving tokens.
- ▸"Convert all this % formatting and .format() to f-string"
- ▸"Apply the debug expression (f'{x=}') to this f-string"
Why does this reduce tokens
Without understanding the concept, even after receiving an AI response you have to ask 'What does that mean?' again. That follow-up question is what consumes tokens. Learn the concept once, and the conversation ends in a single exchange.