October 2018
Beginner to intermediate
466 pages
12h 2m
English
While these standard formatters apply to most built-in objects, it is also possible for other objects to define nonstandard specifiers. For example, if we pass a datetime object into format, we can use the specifiers used in the datetime.strftime function, as follows:
import datetime
print("{the_date:%Y-%m-%d %I:%M%p }".format(
datetime.datetime.now()))
It is even possible to write custom formatters for objects we create ourselves, but that is beyond the scope of this book. Look into overriding the __format__ special method if you need to do this in your code.
The Python formatting syntax is quite flexible but it is a difficult mini-language to remember. I use it every day and still occasionally have to look up forgotten ...