Python Tutorial - String Formatting
๐จ String Formatting - Pretty Text Banao
๐ Real Life Mein:
Messages format karna:
๐ณ "Dear Rohan, Your bill is โน500"
๐ง "Hello Simran, Your order #123 is shipped"
๐ซ "Ticket: Row 5, Seat 12, Price โน300"
Variables ko text mein daalna = String Formatting!
๐ Formatting Methods
Method 1: Concatenation (+)
name = "Rohan"
age = 15
# Old way - difficult
message = "Hello " + name + ", you are " + str(age) + " years old"
print(message)
Method 2: f-strings (Modern - Best!)
name = "Rohan"
age = 15
# f-string - Easy aur clean!
message = f"Hello {name}, you are {age} years old"
print(message)
# Math bhi kar sakte ho
price = 100
discount = 20
print(f"Price: โน{price - discount}")
๐ฐ Bill Generator Example
Restaurant Bill
customer = "Amit"
item1 = "Pizza"
item2 = "Coke"
price1 = 200
price2 = 50
# Bill format
print("=" * 30)
print(f"Customer: {customer}")
print("=" * 30)
print(f"{item1:<15} โน{price1:>6}")
print(f"{item2:<15} โน{price2:>6}")
print("-" * 30)
total = price1 + price2
print(f"Total{"":<10} โน{total:>6}")
print("=" * 30)
๐ฏ Formatting Options:
{name:10}- 10 characters wide{price:.2f}- 2 decimal places{num:05d}- 5 digits, leading zeros
Example
name = "Python"
version = 3.12
print(f"I love {name} {version}")