209. Writing Custom Python Formatters
class Currency:
def __init__(self, amount):
self.amount = amount
def __format__(self, format_spec):
return f"${self.amount:,.2f}" if format_spec == "currency" else str(self.amount)
price = Currency(12345.678)
print(f"Total: {price:currency}") # Total: $12,345.68🔹 2. Formatting Dates in Custom Format
from datetime import datetime
class CustomDate:
def __init__(self, dt):
self.dt = dt
def __format__(self, format_spec):
formats = {
"short": "%d-%m-%Y",
"long": "%A, %d %B %Y",
}
return self.dt.strftime(formats.get(format_spec, "%Y-%m-%d"))
today = CustomDate(datetime(2024, 8, 25))
print(f"Date (short): {today:short}") # Date (short): 25-08-2024
print(f"Date (long): {today:long}") # Date (long): Sunday, 25 August 2024🔹 3. Custom Formatter for Percentage Representation
🔹 4. Custom Formatter for Hex, Binary, and Octal
🔹 5. Custom Formatter for Human-Readable File Sizes
🔹 6. Formatting Phone Numbers
🔹 7. Custom Formatter for Temperature Conversion
🔹 8. Custom Formatter for Masking Sensitive Data
🔹 9. Custom Formatter for Text Alignment
🔹 10. Custom Formatter for JSON Pretty Printing
Last updated