SwadhyAI Notes

All Python notes

Python String Formatting 📝

F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the fastest and most readable way to format strings. Just prefix the string with f and use {} for variables.

🧩 Analogy: Mad Libs

Think of string formatting like playing Mad Libs.
- You have a sentence with blanks: "Hello, my name is ____ and I like ____."
- You fill in the blanks with variables: name and hobby.
- The result is a complete, custom sentence.

✨ Basic Usage

python
name = "Alice"
age = 30
print(f"Hello, my name is {name} and I am {age} years old.")

🔢 Number Formatting

You can format numbers directly inside the placeholders.

python
price = 59.9999
print(f"Price: {price:.2f}") # Price: 60.00 (Fixed point)

percent = 0.25
print(f"Percentage: {percent:.0%}") # Percentage: 25%

big_num = 1000000
print(f"With commas: {big_num:,}") # With commas: 1,000,000

🎯 Real-World Application: Generating Reports

Formatting is crucial when generating text-based reports or logs.

python
users = [("Alice", 500), ("Bob", 1200), ("Charlie", 300)]

print(f"{'Name':<10} | {'Score':>5}")
print("-" * 18)
for name, score in users:
    print(f"{name:<10} | {score:>5}")

📏 Alignment and Padding

You can align text within a specific width.

python
# < Left align, > Right align, ^ Center align
print(f"{'Left':<10} | {'Right':>10} | {'Center':^10}")
print(f"{'A':<10} | {'B':>10} | {'C':^10}")

🧮 Expressions and Debugging

You can evaluate expressions inside f-strings. Python 3.8+ also supports the = specifier for debugging.

python
x = 10
y = 5
print(f"The sum is {x + y}")

# Debugging (prints variable name and value)
print(f"{x=}, {y=}") # x=10, y=5

💡 Legacy Formatting

Before f-strings, we used .format() or % operator. F-strings are generally preferred now for readability and performance.

python
# Old style
print("Hello, {}".format(name))