✍️ Python f-Strings — The Modern Way to Format Strings
f-strings (formatted string literals) are the fastest, most readable way to format strings in Python 3.6+. Master them completely.
f-strings are 2x faster than .format() and 5x faster than %-style formatting. Always prefer f-strings in Python 3.6+.
💻 Code Example:
# Basic f-string name = "santoshtvk" platform = "pynfinity" print(f"Welcome to {platform}, {name}!") # Expressions inside f-strings price = 999 gst = 0.18 print(f"Total: ₹{price * (1 + gst):.2f}") # ₹1178.82 # Dictionary access user = {'name': 'dhruv', 'score': 95} print(f"User: {user['name']}, Score: {user['score']}/100") # Multiline f-string profile = ( f"Name : {name}\n" f"Platform : {platform}\n" f"Score : {user['score']}%" ) print(profile) # Python 3.12+ — f-string debugging with = sign x = 42 print(f"{x=}") # x=42 — prints variable name AND value # Padding & alignment for i, course in enumerate(['Python', 'AI', 'DevOps'], 1): print(f"{i}. {course:<10} {'★' * i}")
| Concept | Key Takeaway |
|---|---|
| {value:.2f} | 2 decimal places for floats |
| {value:>10} | Right-align in 10-char field |
| {value:<10} | Left-align in 10-char field |
| {value:^10} | Center-align in 10-char field |
| {value:,} | Add thousands comma separator (1,000,000) |
| {value!r} | Call repr() on the value |
Keep exploring and happy coding! 🚀