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