C
Python/Intermediate/Lesson 14

f-string — Modern String Formatting (PEP 498)

15 min·theory
This chapter
6/8

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

python
name = "Hong Gil-dong"
age = 28

print(f"{name} is {age} years old")        # Hong Gil-dong is 28 years old
print(f"Next year {age + 1} years old")      # Expression OK

2. Comparison with older styles

python
# ❌ % formatting (Python 2 era)
"%s is %d years old" % (name, age)

# ⚠️ str.format() (Python 2.6+)
"{} is {} years old".format(name, age)

# ✅ f-string (3.6+) — shorter and faster

f"{name} is {age} years old"

code

### 3. Format specifiers

python

pi = 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)

code

### 4. Debugging (3.8+)

python

x = 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

code

### 5. Multi-line and quotes

python

message = 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

Run the concepts above as actual code. The fastest way to learn is to change the values and see for yourself how they behave.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 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.

f-string — Modern String Formatting (PEP 498) - Python