Python - String Format Method Advanced Syntax

Introduction

You can achieve more specific layouts by adding extra syntax in the format string.

For the formatting method, we use a colon after the possibly empty substitution target's identification, followed by a format specifier that can name the field size, justification, and a specific type code.

Here's the formal structure of what can appear as a substitution target in a format string-its four parts are all optional, and must appear without intervening spaces:

{field-name component !conversion-flag :format-spec } 

In this substitution target syntax:

Item Description
field-name an optional number or keyword to identify an argument, can be omitted via relative argument numbering.
component a string of zero or more ".name" or "[index]" references to fetch attributes and indexed values of the argument, can be omitted to use the whole argument value.
conversion-flag starts with a ! if present, which is followed by r, s, or a to call repr, str, or ascii built-in functions on the value, respectively.
format-spec starts with a : if present, which is followed by text that specifies how the value should be presented, including details such as field width, alignment, padding, decimal precision, and so on, and ends with an optional data type code.

The format-spec component after the colon character has a rich format:

[[fill ]align][sign][#][0][width][,][.precision][type-code] 
Item Description
fillany fill character other than { or }
alignmay be <, >, =, or ^, for left alignment, right alignment, padding after a sign character, or centered alignment, respectively;
sign may be +, -, or space; and the , (comma) option requests a comma for a thousands separator.
width and precision as in the % expression,

The format-spec may contain nested {} format strings with field names only, to take values from the arguments list dynamically, which is like the * in formatting expressions.

type-code options allows 'b' type code used to display integers in binary format.

It's equivalent to using the bin built-in call.

It allows a % type code to display percentages.

It uses only d for base-10 integers (i or u are not used here).

The s type code requires a string object argument; omit the type code to accept any type generically.

Code Meaning
s String (or any object's str(X) string)
r Same as s, but uses repr, not str
c Character (int or str)
d Decimal (base-10 integer)
i Integer
u Same as d (obsolete: no longer unsigned)
o Octal integer (base 8)
x Hex integer (base 16)
X Same as x, but with uppercase letters
e Floating point with exponent, lowercase
E Same as e, but uses uppercase letters
f Floating-point decimal
F Same as f, but uses uppercase letters
g Floating-point e or f
G Floating-point E or F

Related Topic