Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

Nested formatting specifications

The string.format() method can handle nested instances of {} to perform simple keyword substitution into the format specification. This replacement is done to create the final format string that's passed to our class __format__() method. This kind of nested substitution simplifies some kinds of relatively complex numeric formatting by parameterizing an otherwise generic specification.

The following is an example where we've made width easy to change in the format parameter:

width=6
for hand,count in statistics.items():
    print( "{hand} {count:{width}d}".format(hand=hand,count=count,width=width) )

We've defined a generic format, "{hand:%r%s} {count:{width}d}", which requires a width parameter to make it into a proper format specification.

The value provided with the width= parameter to the format() method is used to replace the {width} nested specification. Once this is replaced, the final format as a whole is provided to the __format__() method.