String Formatting in Python (Old Style, format(), f-strings)
🚀 Introduction
"Aapne kabhi aisa likha hai?"
print("Hello, %s! You are %d years old." % ("Ravi", 25))
"Ya fir kuch aisa?"
print("Hello {}, you are {} years old.".format("Ravi", 25))
"Aur aajkal sab aisa likhte hai:"
print(f"Hello {name}, you are {age} years old.")
"Toh kaunsa best hai? Aaj karte hain deep comparison of all 3 formatting styles!"
🛠️ Section 1: Old-Style Formatting (% Operator)
name = "Ravi"
age = 25
print("Hello %s, you are %d years old." % (name, age))
- C-style formatting
%s
,%d
,%f
- Strict type match
print("Value is %d" % "not a number") # Error
"Not Pythonic, not recommended now."
⚙️ Section 2: .format() Method
print("Hello {}, you are {} years old.".format(name, age))
print("Hello {0}, your age is {1}, again {0}".format(name, age))
- Positional & keyword args
- Supports alignment, padding, decimal formatting
print("{:>10}".format("Hello"))
print("{:.2f}".format(3.14159))
print("Name: {n}, Age: {a}".format(n="Ravi", a=25))
"Useful in older versions (<3.6)"
⚡ Section 3: f-Strings (Python 3.6+)
name = "Ravi"
age = 25
print(f"Hello {name}, you are {age} years old.")
- Fastest
- Cleanest
- Supports inline expressions
- Debug-friendly
print(f"2 + 2 = {2 + 2}")
person = {"name": "Ravi", "age": 25}
print(f"{person['name']} is {person['age']} years old.")
Python 3.8+ debug trick:
x = 10
print(f"{x=}") # Output: x=10
🔬 Section 4: Formatting Options
price = 123.456
print(f"Price: {price:.2f}") # 123.46
print(f"Hex: {255:x}") # ff
print(f"Binary: {255:b}") # 11111111
Padding & alignment:
print(f"{'Hello':>10}") # right align
print(f"{'Hi':^10}") # center
print(f"{'Bye':<10}") # left
Thousands separator:
print(f"{1000000:,}") # 1,000,000
Combined:
total = 2450.5
print(f"Total Amount: ₹{total:,.2f}")
🧰 Section 5: Real-World Use Cases
- Logging
- Reports
- Templates
- CLI printing
- Debugging
user = {"name": "Amit", "score": 88.455}
print(f"{user['name']:10} | {user['score']:>6.2f}")
⚠ Section 6: Gotchas & Best Practices
- Use f-strings by default (Python 3.6+)
- Use .format() for templates or older versions
Avoid:
print("Name is " + name + " and age is " + str(age))
f-strings multiline issues:
# This will error:
print(f"
Hello {name}
")
# Use wrap or escape:
print(f"Hello {name}\n")
🧠 Section 7: Behind the Scenes
- f-strings use
str.__format__
- Compiled at runtime, fastest of all
- Clean syntax + powerful formatting = win-win!
🎤 Keep it up
"Ab tum master ho string formatting ke! Practice karo aur apne code ko aur readable banao."
"Agla part: Comprehensions & Short-hand syntax 🚀"
Playlist of Python Ka Pitara
1. What is Python? And why are everyone learning Python? #1 || Python Ka Pitara || DeathCodeWatch
2. Python ka Syntax – Itna Simple, It Feels Like English #2 || Python Ka Pitara || DeathCodeWatch
3. Variables and Data Types in Python – Har Detail #3 || Python ka Pitara || DeathCodeWatch
4. Python Conditional – IF ELSE ka Sach & Har Real Use Case! #4 || Python ka Pitara || DeathCodeWatch
5. Python operators – all in one video (with real examples) #5 || Python ka Pitara || DeathCodeWatch
6. Loops in Python – for & while loop (break, continue, pass) #6 || Python ka Pitara || DeathCodeWatch
7. Functions ka Jadoo in Python ✨ | Return, Arguments, Scope & More #7 || Python ka Pitara || DeathCodeWatch
8. Python Scope System 🧬 | LEGB Rule & Function Execution Flow #8 || Python ka Pitara || DeathCodeWatch
9. How Python Executes Code 🔥 | Step-by-Step Flow Explained Simply! #9 || Python ka Pitara || DeathCodeWatch
10. Python Function Parameter Magic ✨ | args, kwargs Deep Explainer #10 || Python ka Pitara || DeathCodeWatch
11. Python f-Strings Explained | Old % Style vs .format() vs f"" 🔍 #11 || Python ka Pitara || DeathCodeCurrently Playing
12. Master Python Comprehensions 🧠 | One-Liner Magic for Clean Code #12 || Python ka Pitara || DeathCodeWatch
13. Python Functional Tools 🧠 | Dive into map, filter, zip, etc. #13 || Python ka Pitara || DeathCodeWatch
14. Python Modules & Virtual Environments 🔍 | pip Introduction #14 || Python ka Pitara || DeathCodeWatch
15. Essential Python Modules 🔥 | time, random, os, secrets & More #15 || Python ka Pitara || DeathCodeWatch
16. Master File Handling in Python 🔥 | with-as, Modes Explained! #16 || Python ka Pitara || DeathCodeWatch
17. try, except, finally in Python 🔍 Real Examples & Secrets #17 || Python ka Pitara || DeathCodeWatch
18. Everything in Python is an Object 💡 Internals Explained #18 || Python ka Pitara || DeathCodeWatch
19. Python Garbage Collector, Heap & Stack Full Breakdown #19 || Python ka Pitara || DeathCodeWatch
20. Mutable vs Immutable in Python Explained Deeply #20 || Python ka Pitara || DeathCodeWatch
21. Function Execution & Call Stack in Python #21 || Python ka Pitara || DeathCodeWatch
22. Python Interpreter & PVM Behind the Scenes #22 || Python ka Pitara || DeathCodeWatch
23. How Python Imports Modules & Packages #23 || Python ka Pitara || DeathCodeWatch