Format Operator (%)

One of Python’s coolest features is the string format operator. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. In fact, it even uses the same symbol, the percent sign (%), and supports all the printf()
formatting codes.
The syntax for using the format operator is as follows:

format_string % (arguments_to_convert)

The format_string on the left-hand side is what you would typically find as the first argument to printf(), the format string with any of the embedded % codes. The set of valid codes is given in following Table. The arguments_to_convert parameter matches the remaining arguments you would send to printf(), namely the set of variables to convert and display.

Example (Format Operator Conversion Symbols)

Format Symbol Conversion
string conversion via str() prior to formatting
signed decimal integer
signed decimal integer
unsigned decimal integer
octal integer
hexadecimal integer (lowercase letters)
hexadecimal integer (UPPERcase letters)
exponential notation (with lowercase ‘e’)
exponential notation (with UPPERcase ‘E’)
floating point real number
the shorter of %f and %e
the shorter of %f and %E

You may also like...