Custom Formatters
Learn about custom formatters and get hands-on experience using the coding example.
We'll cover the following...
Overview
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:
Press + to interact
import datetimeimportant = datetime.datetime(2019, 10, 26, 13, 14)formatted_date = f"{important:%Y-%m-%d %I:%M%p}"print(formatted_date)
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 we need to do this in our code.
The Python formatting syntax is quite flexible, but it is ...