🕯️ Magic Note
F-strings are the newest and most recommended way to format strings in Python. They are fast, readable, and elegant. But you will see old code using the other methods, so understanding all of them is important. Choose f-strings for your own code whenever possible.
Python
name = “Feloriya”
score = 100
# This works (all strings)
message = “Hello, ” + name + “!”
print(message) # Hello, Feloriya!
# This fails (string + integer)
# message = “Score: ” + score # TypeError
# Fix: convert number to string
message = “Score: ” + str(score)
print(message) # Score: 100
| Format Specifier | What It Does | Example |
|---|---|---|
| %s | String (or any type converted to string) | “Hello %s” % “Feloriya” → “Hello Feloriya” |
| %d | Integer | “Age: %d” % 25 → “Age: 25” |
| %f | Float | “Price: %f” % 19.99 → “Price: 19.990000” |
| %.2f | Float with 2 decimal places | “Price: %.2f” % 19.99 → “Price: 19.99” |
| %x | Hexadecimal | “Hex: %x” % 255 → “Hex: ff” |
Python
name = “Feloriya”
age = 25
price = 19.99
# Basic formatting
print(“Hello %s” % name) # Hello Feloriya
print(“Age: %d” % age) # Age: 25
print(“Price: %.2f” % price) # Price: 19.99
# Multiple values (must be in a tuple)
print(“Name: %s, Age: %d” % (name, age)) # Name: Feloriya, Age: 25
Python
name = “Feloriya”
age = 25
score = 95.5
# Positional arguments
print(“Hello {}!”.format(name))
# Hello Feloriya!
print(“Name: {}, Age: {}”.format(name, age))
# Name: Feloriya, Age: 25
# Positional with indices (can repeat)
print(“{0} {0} {0}”.format(“ha”))
# ha ha ha
# Keyword arguments
print(“Name: {n}, Age: {a}”.format(n=name, a=age))
# Name: Feloriya, Age: 25
🕯️ Magic Note
You can specify formatting inside the placeholders. For example: {:.2f} for two decimal places, {:d} for integers, {:10} for width, {:>10} for right alignment.
Python
# Format specifiers inside {}
pi = 3.14159265
print(“Pi: {:.2f}”.format(pi)) # Pi: 3.14
print(“Pi: {:.4f}”.format(pi)) # Pi: 3.1416
# Width and alignment
print(“{:>10}”.format(“right”)) # right
print(“{:<10}”.format(“left”)) # left
print(“{:^10}”.format(“center”)) # center
# Numbers with width and padding
print(“{:05d}”.format(42)) # 00042
print(“{:+,}”.format(1000000)) # +1,000,000
Python
name = “Feloriya”
age = 25
score = 95.5
# Basic f-string
print(f”Hello {name}!”)
# Hello Feloriya!
print(f”Name: {name}, Age: {age}”)
# Name: Feloriya, Age: 25
# You can put expressions inside {}
print(f”Next year you will be {age + 1}”)
# Next year you will be 26
print(f”Score: {score:.2f}”)
# Score: 95.50
# Call methods inside {}
print(f”Uppercase: {name.upper()}”)
# Uppercase: FELORIYA
🕯️ Magic Note
F-strings are evaluated at runtime. You can put any valid Python expression inside the curly braces: {len(name)}, {name.strip().lower()}, {a + b * c}. This makes them incredibly powerful.
Python
# Complex expressions in f-strings
x = 5
y = 10
print(f”{x} + {y} = {x + y}”)
# 5 + 10 = 15
words = [“magic”, “spells”, “conjure”]
print(f”Number of words: {len(words)}”)
# Number of words: 3
# Conditional inside f-string
score = 85
print(f”Result: {‘Pass’ if score >= 60 else ‘Fail’}”)
# Result: Pass
Python
num = 1234.56789
percentage = 0.856
large = 1234567
# Two decimal places
print(f”{num:.2f}”) # 1234.57
print(“{:.2f}”.format(num)) # 1234.57
print(“%.2f” % num) # 1234.57
# Percentage
print(f”{percentage:.1%}”) # 85.6%
# Comma as thousands separator
print(f”{large:,}”) # 1,234,567
# Width and padding
print(f”{num:10.2f}”) # 1234.57 (width 10, right aligned)
print(f”{num:<10.2f}”) # 1234.57 (left aligned)
Python
name = “Feloriya”
skill = “Python”
level = “intermediate”
# Multi-line f-string (with triple quotes)
message = f”””
=== Wizard Profile ===
Name: {name}
Skill: {skill}
Level: {level}
====================
“””
print(message)
- Forgetting the f prefix: “Hello {name}” prints literally, not the value
- Mixing up % syntax: “%s %d” % (text, num) requires parentheses
- Using f-strings in Python versions older than 3.6 (they will cause SyntaxError)
- Forgetting to convert numbers to strings with + concatenation
- Putting too many expressions inside f-string braces (keep them simple and readable)
- Using .format() with wrong number of arguments (too few or too many)
| Method | When to Use | Example |
|---|---|---|
| + | Very simple joins (2-3 parts, all strings already) | “Hello ” + name |
| % | Old code maintenance or very simple formatting | “Age: %d” % age |
| .format() | Python 3.5 or earlier, or when you need advanced formatting options | “Name: {}”.format(name) |
| f-strings | Python 3.6+ (most code today) – always prefer this | f”Name: {name}” |
- Write an f-string that prints “Hello, [name]! You are [age] years old.”
- How do you format a float to two decimal places using an f-string?
- What happens if you forget the f before an f-string?
- Why is .join() better than + for joining many strings?
- Convert “Score: {}” to an f-string.
- What is the output of f”Value: {10 * 2}”?
⚡ Whisper
A formatted string is a message waiting to be completed. You write the skeleton with empty spaces. Later, you fill those spaces with names, numbers, and whispered secrets. The old ways use % like ancient runes. The new ways use {} like open hands. But the f-string is the true magic of our time. You speak the variable name directly inside the string, and Python understands. Choose your method wisely. But always choose readability. A clear message is worth more than a clever trick.