Format() in Python
Today I’m going to write about formatting of strings in Python using format()
function.
Sending out a root mail(in BITS) got me inspired to write an article on it. So here’s something for my (and maybe even for your ) future reference.
Basic formatting
Output
You can give placeholders an explicit positional index.
Output
Value conversion
The new-style simple formatter calls by default the __format__()
method of an object for its representation.
If you just want to render the output of str(…)
or repr(…) you can use the !s
or !r
conversion flags.
Setup
Input
Output
Padding and aligning strings
By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length. Default alignment is left.
Output
By default string is being padded by space. But you can choose the padding character.
Output
You can align in center as well
Output
When using center alignment where the length of the string leads to an uneven split of the padding characters the extra character will be placed on the right side.
Output
Truncating long strings
Inverse to padding it is also possible to truncate overly long values to a specific number of characters.
Output
Combining truncating and padding
It is possible to combine truncating and padding.
Output
Numbers
It is possible to do padding with numbers.
Output
Again similar to truncating strings the precision for floating point numbers limits the number of positions after the decimal point.
For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.
Output
Named placeholders
Setup
Input
Output
.format() also accepts keyword arguments.
Output
Getitem and Getattr
New style formatting allows even greater flexibility in accessing nested data structures.
It supports accessing containers that support __getitem__
like for example dictionaries and lists:
Setup
Input
Output
Setup
Input
Output
Datetime
Setup
Input
Output
Parametrized formats
Output
Output
Output
Setup
Input
Output
Custom objects
The datetime example works through the use of the __format__()
magic method. You can define custom format handling in your own objects by overriding this method. This gives you complete control over the format syntax used.
Setup
Input
Output
This post was originally written by me on gujjucoders.me.