209. Writing Custom Python Formatters
🔹 1. Basic Custom Formatter Using __format__
We override the
__format__method in a class.
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🔍 How it works:
If
"currency"format is used, it returns a formatted string with$and two decimal places.
🔹 2. Formatting Dates in Custom Format
We format a
datetimeobject using a custom formatter.
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🔍 How it works:
Provides multiple date formats based on the format specifier.
🔹 3. Custom Formatter for Percentage Representation
🔍 How it works:
The
"percent"format multiplies the value by 100 and appends%.
🔹 4. Custom Formatter for Hex, Binary, and Octal
🔍 How it works:
Uses different format specifiers to convert numbers to hex, binary, and octal.
🔹 5. Custom Formatter for Human-Readable File Sizes
🔍 How it works:
Automatically converts bytes into KB, MB, GB, etc. for readability.
🔹 6. Formatting Phone Numbers
🔍 How it works:
Formats a phone number based on a country-specific format.
🔹 7. Custom Formatter for Temperature Conversion
🔍 How it works:
Converts Celsius to Fahrenheit and Kelvin based on the format specifier.
🔹 8. Custom Formatter for Masking Sensitive Data
🔍 How it works:
Masks all characters except the last 4 for privacy.
🔹 9. Custom Formatter for Text Alignment
🔍 How it works:
Aligns text left, center, or right using
-as a padding character.
🔹 10. Custom Formatter for JSON Pretty Printing
🔍 How it works:
Returns pretty-printed JSON when the
"pretty"format is used.
Last updated