Python String Formatting
🧵 Python String Formatting
String formatting means inserting values into a string in a clean and readable way.
Python supports 4 main formatting methods:
-
f-strings(Recommended, fastest) -
format()method -
%formatting (Old style) -
Template Strings(less common but safe)
✅ 1. F-Strings (Best Way — Python 3.6+)
💡 Supports expressions:
💡 With formatting:
🧮 Format Numbers
| Format | Usage | Example |
|---|---|---|
{:.2f} |
2 decimals | 3.14159 → 3.14 |
{:,.2f} |
Commas + decimals | 10000 → 10,000.00 |
{:b} |
Binary | 5 → 101 |
{:x} |
Hexadecimal | 16 → 10 |
Example:
🧩 2. .format() Method
Positional & Named Formatting
Using indexes:
Named arguments:
🎨 Format Numbers with .format()
🧓 3. % Formatting (Old Style)
| Symbol | Meaning |
|---|---|
%s |
string |
%d |
integer |
%f |
float |
Formatting floats:
🛡 4. Template Strings (From string module)
Useful in financial or user input-sensitive programs.
📍 Alignment & Formatting
| Syntax | Meaning |
|---|---|
{:>10} |
Right align |
{:<10} |
Left align |
{:^10} |
Center align |
Example:
🔥 Real Example
📌 Summary Table
| Method | Use Case | Modern Use |
|---|---|---|
| F-string | Best, fast, clean | ⭐⭐ Recommended |
.format() |
Flexible formatting | ⭐ Used |
% formatting |
Old Python | ⚠ Legacy |
| Template Strings | Secure formatting | ⭐ Special use |
🧠 Practice Tasks
✔ Format currency with commas
✔ Display a table using alignment
✔ Create a dynamic message using user input
✔ Convert number to binary & hex using formatting
