目录
{0[Jack]:d}中 :d 的作用:
{0[Jack]:d}中 0 的作用:
>>> t0 = {'Sjoerd': 10, 'Jack': 20, 'Dcab': 30}
>>> t1 = {'Sjoerd': 11, 'Jack': 21, 'Dcab': 31}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(t0))
Jack: 20; Sjoerd: 10; Dcab: 30
>>> print('Jack: {0[Jack]:d}'.format(t0))#十进制
Jack: 20
>>> print('Jack: {0[Jack]}'.format(t0))#默认
Jack: 20
>>> print('Jack: {0[Jack]:x}'.format(t0))#十六进制
Jack: 14
>>> print('Jack: {0[Jack]:d}; Jack: {1[Jack]:d}'.format(t0,t1))
Jack: 20; Jack: 21
下面的程序也说明了不省略 :d 的好处
>>> for x in range(1, 11):
#等价形式print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
print('{0:2} {1:3} {2:4}'.format(x, x*x, x*x*x))
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
下面这个例子又有了新认识
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
help('FORMATTING')