PEP 3101 specifies Advanced String Formatting. Among other things, it defines a specification of a new syntax for format strings (eg. {:.2f}
) and how custom types can control their own formatting. This is done by implementing:
def __format__(value, format_spec):
# Your code here
The string formatting code can include a conversion flag. For example: "{0!r:20}".format("Hello")
, where !r
means convert the the value to a string using repr()
. However, __format__
only gets the value after the colon :
(i.e. the format_spec). I would like to know is the reason (i.e. the design decision, not the code) why? I think that providing everything after the the !
will be more flexible.