209. Writing Custom Python Formatters
🔹 1. Basic Custom Formatter Using __format__
__format__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
🔹 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