Document the __format__ magic method #26

Closed
rhettinger opened this Issue Apr 8, 2012 · 0 comments

Projects

None yet

2 participants

@rhettinger

This important method makes it possible to control/override/extend the new-style string formatting.

For example, you can create a subclass of int that prints numbers with underscores between the digits:

>>> import re
>>> class UnderInt(int):
        def __format__(self, fmtstr):
                mo = re.search(r'(\d+)d', fmtstr)
                if mo:
                        width = int(mo.group(1))
                        return '_'.join(str(int(self)))
                return int.__format__(self, fmtstr)


>>> print 'There are {0:10d} characters'.format(123456)
There are     123456 characters
>>> print 'There are {0:10d} characters'.format(UnderInt(123456))
There are 1_2_3_4_5_6 characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment