Python - String Format Method: Adding Keys, Attributes, and Offsets


format method calls can support more advanced usage.

The following examples indexes a dictionary on the key "test" and then fetches the attribute "platform" from the already imported sys module object.

The second does the same, but names the objects by keyword instead of position:


import sys 
print( 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'}) )
print( 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'}) )


Square brackets in format strings can name list offsets to perform indexing.

To name negative offsets or slices, or to use arbitrary expression results in general, you must run expressions outside the format string itself:


somelist = list('TEST') 
print( somelist )
print( 'first={0[0]}, third={0[2]}'.format(somelist) )

print( 'first={0}, last={1}'.format(somelist[0], somelist[-1]) )   # [-1] fails in fmt 
#   ww w . j  a  v  a2s .  co m
parts = somelist[0], somelist[-1], somelist[1:3]           # [1:3] fails in fmt 
print( 'first={0}, last={1}, middle={2}'.format(*parts) )          # Or '{}' in 2.7/3.1+


Related Topic