164. Custom String Interpolation

Snippet 1: Custom Formatting for a Class

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __format__(self, format_spec):
        if format_spec == 'short':
            return f"{self.name[0]}. ({self.age})"
        return f"{self.name}, Age: {self.age}"

# Create a Person instance
person = Person("Alice", 30)

# Custom format: short version
print(f"{person:short}")

# Default format
print(f"{person}")

Snippet 2: Custom Currency Formatting


Snippet 3: Custom Date Formatting


Snippet 4: Custom Percentage Formatting


Snippet 5: Custom String Formatting for a Rectangle Class


Snippet 6: Custom Time Duration Formatting


Snippet 7: Custom IP Address Formatting


Snippet 8: Custom Formatting for a Student Class


Snippet 9: Custom List Formatting


Snippet 10: Custom Hexadecimal Formatting


Last updated