The part of
a format code specifies the source of the value to be
formatted here. Numbers refer to positional arguments
passed to the name.format() method, starting at 0
for the first argument. You may also use any Python name to refer to one of the keyword
arguments.
If the associated argument is an iterable, you may append an expression of this form to retrieve one of its elements:
"[" index "]"
For example:
>>> signal=['red', 'yellow', 'green']
>>> signal[2]
'green'
>>> "The light is {0[2]}!".format(signal)
'The light is green!'
If the associated argument has attributes, you can append an expression of this form to refer to that attribute:
"."name
For example:
>>> import string
>>> string.digits
'0123456789'
>>> "Our digits are '{s.digits}'.".format(s=string)
"Our digits are '0123456789'."
In general, you can use any combination of these features. For example:
>>> "The sixth digit is '{s.digits[5]}'".format(s=string)
"The sixth digit is '5'"
Starting with Python 2.7, you may omit all of the numbers that refer to positional arguments, and they will be used in the sequence they occur. For example:
>>> "The date is {}-{}-{}.".format(2012, 5, 1)
'The date is 2012-5-1.'
If you use this convention, you must omit all those numbers. You can, however, omit all the numbers and still use the keyword names feature:
>>> "Can I have {} pounds to {excuse}?".format(
... 50, excuse='mend the shed')
'Can I have 50 pounds to mend the shed?'