A format string contains replacement fields that determine where supplied values appear in formatted text. In Python, the string’s format method substitutes its arguments into fields marked by braces. Double the braces, as in {{ or }}, to include literal braces. section 6.6
Numbered fields select positional arguments: {0} always refers to the first argument, wherever it appears. Fields can also use named arguments. section 6.6.1
"{0} is the {1} of {2}".format("Ambrosia", "food", "the gods") #1
'Ambrosia is the food of the gods'
"{{Ambrosia}} is the {0} of {1}".format("food", "the gods") #2
'{Ambrosia} is the food of the gods'
#1 The format method is applied to the format string, which can also be a string variable.
#2 Doubling the { } characters escapes them so that they don’t mark a replacement field.
The first example uses numbered fields; the second escapes braces around literal text. section 6.6.1
A format specifier after a colon controls the substituted value’s appearance, including fill, alignment, sign, width, precision, and type. A field’s width can itself come from another argument. section 6.6.3
"{0:10} is the food of gods".format("Ambrosia") #1
'Ambrosia is the food of gods'
"{0:{1}} is the food of gods".format("Ambrosia", 10) #2
'Ambrosia is the food of gods'
"{food:{width}} is the food of gods".format(food="Ambrosia", width=10)
'Ambrosia is the food of gods'
"{0:>10} is the food of gods".format("Ambrosia") #3
' Ambrosia is the food of gods'
"{0:&>10} is the food of gods".format("Ambrosia") #4
'&&Ambrosia is the food of gods'
#1 :10 makes the field 10 spaces wide, padded with spaces.
#2 :{1} width is from the second parameter.
#3 :>10 forces right justification.
#4 :&>10 forces right justification padded with & character.
Compare fixed and argument-supplied widths with right alignment and a custom fill character. section 6.6.3
F-strings also use braces and support format specifiers, but evaluate Python expressions without an explicit format() call. Older % formatting uses a different syntax; named sequences can select values from a dictionary. section 6.7 section 6.8.2
The term also appears in Python’s struct module with a different meaning: a struct format string describes the types and layout of a packed binary record, rather than replacement fields in text. For example, 'hd7s' specifies a C short, a C double, and a seven-character string. section 13.7






