Python f-Strings Explained | Old % Style vs .format() vs f"" 🔍 #11 || Python ka Pitara || DeathCode - DeathCode

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 🚀"

© 2024 DeathCode. All Rights Reserved.