Defining a custom __format__ method in Python? Go bananas, if you want. For example (see image for full demo):
Defining __format__ in a Python class? Check if the second argument is ”, meaning no format code:
Want your Python class to take custom format codes? Define __format__. This method returns self.x *except* with a :< format. Then it reverses self.x:
A Python value x in an f-string’s {} normally interpolates str(x), aka x.__str__. Want the repr instead, aka x.__repr__? Put !r after the value: f'{x}’ # returns str(x)f'{x!s}’ # also returns str(x), but unneededf'{x!r}’ # returns the repr
Have a Python datetime, and want to print it? Use an f-string, and pass a strftime-style format: f'{now:%Y-%m-%d}’ # year-month-datef'{now:%Y-%m-%d %H:%M:%S}’ # year-month-date hour:min:sec # Easily integrate into user outputf’Today is {now:%Y-%m-%d}, you know!’
Have a Python number, and want commas before every 3 digits? Use , in an f-string: Floats, too: Combine , and .2f:
Have a Python float, and want to show it as a percentage? Use % in an f-string
Want to display a Python float with a limited number of decimals? Use .nf as an f-string’s format specifier. n is the number of digits to show after the decimal: Note: It rounds the final digit!
Use Python f-strings and format specifiers to make quick-and-dirty tables: Output: a…….10bcd……2e…..3456
A Python f-string can have a “format specifier,” one or more characters after : that dictate the format. For example, you can use < ^ and > with an integer to justify the text: