Format with conversion (stringifiation with str or repr)


Adding !s or !r in the place-holder we tell it to cal the str or repr method of the object, respectively.


examples/format/format_no_conversion.py
class Point:
    def __init__(self, a, b):
        self.x = a
        self.y = b

p = Point(2, 3)
print(p)                 # <__main__.Point object at 0x10369d750>
print("{}".format(p))    # <__main__.Point object at 0x10369d750>
print("{!s}".format(p))  # <__main__.Point object at 0x10369d750>
print("{!r}".format(p))  # <__main__.Point object at 0x10369d750>

examples/format/format_conversions.py
class Point:
    def __init__(self, a, b):
        self.x = a
        self.y = b
    def __format__(self, spec):
        #print(spec) // empty string
        return("{{'x':{}, 'y':{}}}".format(self.x, self.y))
    def __str__(self):
        return("({},{})".format(self.x, self.y))
    def __repr__(self):
        return("Point({}, {})".format(self.x, self.y))

p = Point(2, 3)
print(p)                 # (2,3)
print("{}".format(p))    # {'x':2, 'y':3}
print("{!s}".format(p))  # (2,3)
print("{!r}".format(p))  # Point(2, 3)