字符串格式化
1.字典字符串格式化
>>> '%(a)s %(b)s' % {'a':'fruit','b':'apple'}
'fruit apple'
2.>>> hello='''hello %(name)s !
your age is %(age)s
'''
>>> values={'name':'bob','age':25}
>>> print {hello%values}
set(['hello bob !\n your age is 25\n '])
3.food='i like eat {0},{fruit} and {1}'
>>> food.format('eggs','apple',fruit='pear')
'i like eat eggs,pear and apple'
4.package='{tuple},{0} and {list}'.format('python',tuple='123',list=[1,2,3])
>>>package.split('and')
['123,python ', ' [1, 2, 3]']
>>> package.replace('python','is not equl')
'123,is not equl and [1, 2, 3]'
5.>>> import sys
>>> 'my {1[os]} runs {0.platform}'.format(sys,{'os':'win'})
'my win runs win32'
>>> 'my {config[os]} runs {s.platform}'.format(s=sys,config={'os':'win'})
'my win runs win32'
6.>>> slist=list('spam')
>>> parts=slist[0],slist[1],slist[1:3] #列表分片半开半闭
>>> '{0},{1},{2}'.format(*parts)
"s,p,['p', 'a']"
7.>>> '{0:>10}={1:<10}'.format('bob',123.123) #左对齐
' bob=123.123 '
8.>>> '{0.platform} is {1[os]}'.format(sys,dict(os='win'))
'win32 is win'
9.
>>> bin(255),int('11111111',2),0b11111111
('0b11111111', 255, 255)
>>> hex(255),int('FF',16),0xFF
('0xff', 255, 255)
>>> oct(255),int('377',8),0o377,0377
('0377', 255, 255, 255)
10.
>>> '{0:.2f}'.format(1/3.0)
'0.33'
>>> '%.2f' % (1/3.0)
'0.33'
>>> '{0:.{1}f}'.format(1/3.0,4)
'0.3333'
>>> '%.*f' % (4,1/3.0) # 利用‘’*f‘’先取%右边第一个为width参数
'0.3333'