'{:<30}'.format('left aligned')
'left aligned '
'{:>30}'.format('right aligned')
' right aligned'
'{:^30}'.format('centered')
' centered '
'{:*^30}'.format('centered') # use '*' as a fill char
'*********centered*********'
15 format()15.1 基本格式{fieldname ! conversionflag : formatspec}fieldname: number(a potitional argument) or keyword(named keyword argument) .name or [index] "Weight in tons {0.weight}" "Units destroyed: {players[1]}"conversionflag: s r a ==>str repr asciiformatspec: [[fill]align[sign] [#] [0] [width] [.percision] [typecode]] fill ==> 除{} 外的所有字符都可以 align==> > < = ^ sign ==> '+' '-' ' ' '-' 为默认情况 正数不显示+负数显示- '+'表正负数都显示符号 'space' 表示数字前面显示一空格 width precision ==> integer type ==> b c d e E f F g G n o 15.2 Accessing arguments by potition:>>> print '{0} {1} {2}'.format('a', 'b', 'c')a b c>>> '{2}, {1}, {0}'.format(*'abc') ### 'c, b, a'>>> 'My {1[spam]} runs {0.platform}'.format(sys, {'spam': 'laptop'})'My laptop runs linux2'15.3 Accessing arguments by name:>>> 'Coordinates: {latitude}, {longtitude}'.format(latitude = '23.2N', longtitude = '-112.32W')'Coordinates: 23.2N, -112.32W'>>> coord = {'latitude': '23.12N', 'longtitude': '-23.23W'}>>> 'Coordinates: {latitude}, {longtitude}'.format(coord)'Coordinates: 23.12N, -23.23W'>>> print '{name} {age}'.format(age=12, name='admin')admin 12>>> 'My {config[spam]} runs {sys.platform}'.format(sys=sys, config={'spam': 'laptop'})'My laptop runs linux2'15.4 Accessing arguments' attributes:>>> c = 3 -5j>>> 'The complex number {0} is formed from the real part {0.real} and the imaginary part {0.imag}'.format(c)'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0'15.5 Accessing argument's items:>>> coord = (3, 5)>>> 'X: {0[0]}; Y: 0[1]'.format(coord)'X: 3; Y: 0[1]'>>> print '{array[2]}'.format(array=range(10))215.6 !s !r>>> "repr() show quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')"repr() show quotes: 'test1'; str() doesn't: test2"15.7 Aligning the text and specifying a width>>> '{: <30}'.format('left aligned')'left aligned '>>> '{: >30}'.format('right aligned')' right aligned'>>> '{: ^30}'.format('centered')' centered '>>> '{:^30}'.format('centered')'*********centered*********'15.8 +f -f>>> '{:-f}; {:-f}'.format(3.14, -3.14)'3.140000; -3.140000'>>> '{:+f}; {:+f}'.format(3.14, -3.14)'+3.140000; -3.140000'>>> '{:f}; {:f}'.format(3.14, -3.14)'3.140000; -3.140000'15.9 b o x>>> 'int: {0: d}; hex: {0: x}; oct: {0: o}; bin{0: b}'.format(42)'int: 42; hex: 2a; oct: 52; bin 101010'# # with 0x, 0o, or 0b as prefix:>>> 'int: {0: d}; hex: {0: #x}; oct: {0: #o}; bin{0: #b}'.format(42)'int: 42; hex: 0x2a; oct: 0o52; bin 0b101010'15.10 Using , as a thousand seperator>>> '{: ,}'.format(12345678)' 12,345,678'15.11 More==>Refer to doc-pdf(Python 参考手册)-library.pdf–>String services.>>> print '{attr.__class__}'.format(attr=0)