F-strings (formatted string literals) are Python’s way of embedding expressions inside string literals, introduced in Python 3.6. They are prefixed with f
or F
.
Basic Example:
name = "Alice"
print(f"Hello, {name}!") # Output: Hello, Alice!
Python 3.12 made f-strings more flexible by removing several restrictions.
Old Behavior (Python 3.11 and earlier):
# This would cause a SyntaxError
print(f"Hello {"world"!r}") # ❌ Error: Can't reuse double quotes
New Behavior (Python 3.12+):
print(f"Hello {"world"!r}") # ✅ Now works! Output: Hello, 'world'
Old Behavior:
New Behavior (Python 3.12+):
name = "Bob"
message = f"""
Hello, {
name.upper() # Arbitrary expressions
}!
"""
print(message)
# Output:
# Hello,
# BOB
# !
\
) Allowed Inside F-StringsOld Behavior:
# This would cause a SyntaxError
path = f"C:\Users\{username}" # ❌ Error: Invalid escape sequence
New Behavior (Python 3.12+):
username = "Alice"
path = f"C:\Users\{username}" # ✅ Now works!
print(path) # Output: C:\Users\Alice
✅ Cleaner code – No need to escape quotes or split f-strings into multiple parts.
✅ Better readability – Multi-line f-strings make complex formatting easier.
✅ More intuitive – Fewer restrictions mean fewer surprises.
| Feature | Old Behavior (≤ Python 3.11) | New Behavior (Python 3.12+) |
|———|—————————–|—————————–|
| Reusing Quotes | SyntaxError
| ✅ Works (f"Hello {"world"}"
) |
| Multi-line F-strings | Not allowed | ✅ Works with indentation |
| Backslashes (\
) | SyntaxError
| ✅ Works (f"C:\path"
) |
Example to Try:
# Multi-line f-string with calculations
result = f"""
The sum of 5 and 10 is {
5 + 10
}, and the product is {
5 * 10
}.
"""
print(result)
These changes make f-strings even more powerful while keeping them simple.
Which feature do you find most useful? Let me know if you’d like more examples! 🚀