Thursday, November 13, 2025

f-strings in Python( starting from easy → medium → hard)

 

🟒 LEVEL 1: EASY — What is an f-string?

An f-string (formatted string literal) allows you to insert variables directly inside a string using {}.

✅ Basic syntax

name = "Raghav" print(f"My name is {name}")

Output:

My name is Raghav

🟒 Why use f-strings?

  • Easier than + concatenation

  • Faster than format()

  • Looks cleaner


🟑 LEVEL 2: MEDIUM — Using Expressions in f-strings

You can insert calculations or functions inside { }.

Example:

a = 10 b = 5 print(f"Sum = {a+b}")
print(f"Uppercase: {'hello'.upper()}")
import math print(f"Square root of 25 is {math.sqrt(25)}")

🟑 Formatting numbers

✔ Decimal formatting

price = 49.5678 print(f"Price: {price:.2f}") # 2 decimal places

✔ Add commas

num = 1000000 print(f"{num:,}")

✔ Percentage

rate = 0.75 print(f"{rate:.0%}")

πŸ”΅ LEVEL 3: HARD — Formatting Alignment & Padding

⭐ Left, Center, Right Alignment

print(f"|{'Apple':<10}|") # left print(f"|{'Apple':>10}|") # right print(f"|{'Apple':^10}|") # center

⭐ Padding with characters

print(f"{5:05}") # 00005 print(f"{42:*^10}") # ****42****

πŸ”΅ Using Dictionaries in f-strings

student = {"name": "Raghav", "age": 20} print(f"Name: {student['name']}, Age: {student['age']}")

πŸ”΅ Nested f-strings (tricky but powerful)

name = "Raghav" style = "upper" print(f"{name.{style}()}") # ❌ This will not work

Correct way:

print(f"{getattr(name, style)()}")

🟣 LEVEL 4: ADVANCED — Using f-strings for debugging

Python 3.8+ allows:

x = 10 y = 20 print(f"{x=}, {y=}")

Output:

x=10, y=20

This is extremely useful for debugging.


🟣 Embedding conditional (if) in f-strings

age = 18 print(f"You are {'adult' if age >= 18 else 'minor'}")

🟣 Format dates using f-strings

from datetime import datetime now = datetime.now() print(f"Today is {now:%d-%m-%Y}")

Output:

Today is 14-11-2025

πŸ”΄ LEVEL 5: EXTREME — Using f-strings with classes

class Student: def __init__(self, name, marks): self.name = name self.marks = marks s = Student("Raghav", 95) print(f"Student: {s.name}, Marks: {s.marks}")

πŸ”΄ Custom formatting using __format__

class Money: def __init__(self, amount): self.amount = amount def __format__(self, fmt): if fmt == "INR": return f"₹{self.amount:.2f}" return str(self.amount) m = Money(500) print(f"Total Amount: {m:INR}")

Output:

Total Amount: ₹500.00

🏁 SUMMARY

LevelWhat You Learned
EasyBasic f-string usage
MediumExpressions, functions, number formatting
HardAlignment, padding, dictionary access
AdvancedDebugging, conditions, date formatting
ExpertClasses + custom formatting

No comments:

Post a Comment

Python Viva Questions

  Basic Python Viva Questions 1. What is Python? Python is a high-level, interpreted, and object-oriented programming language used for w...