Nested formatting specifications

The string.format() method can handle nested instances of {} to perform simple keyword substitution into the format specification itself. This replacement is done to create the final format string that's passed to our class's __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(f"{hand} {count:{width}d}") 

We've defined a generic format, f"{hand} {count:{width}d}", which requires a width parameter to make it into a final format specification. In the example, width is 6, which means that the final format will be f"{hand} {count:6d}". The expanded format string, "6d" will be the specification provided to the __format__() method of the underlying object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset