Python版本:Python 2.7.13rc1
1.数字
整型
正确的写法:
>>> print 'The value of PI is approximately %d ' % (3)
The value of PI is approximately 3
>>> print 'The value of PI is approximately {:d} '.format(3)
The value of PI is approximately 3
>>> print 'The value of PI is approximately %d ' % (3.1415926)
The value of PI is approximately 3
错误的写法:
>>> print 'The value of PI is approximately {:d} '.format(3.1415926)
对齐:
>>> print '%4d'%(42)
42
>>> print '{:_>4d}'.format(42)
__42
>>> print '%04d'%(42)
0042
>>> print '{:04d}'.format(42)
0042
浮点型
>>> import math
>>> print 'The value of PI is approximately %f ' % (math.pi)
The value of PI is approximately 3.141593
>>> print 'The value of PI is approximately {:f} '.format(math.pi)
The value of PI is approximately 3.141593
保留小数点后三位:
>>> print 'The value of PI is approximately %.3f ' % (math.pi)
The value of PI is approximately 3.142
>>> print 'The value of PI is approximately {:.3f} '.format(math.pi)
The value of PI is approximately 3.142
显示六个字符,其中包括小数点和小数点后三位,不足六个字符补0:
>>> print 'The value of PI is approximately %06.3f ' % (math.pi)
The value of PI is approximately 03.142
>>> print 'The value of PI is approximately {:06.3f} '.format(math.pi)
The value of PI is approximately 03.142
有正负号的数字
>>> print '%+d' % (42)
+42
>>> print '{:+d}'.format(42)
+42
>>> print '% d' % (-42)
-42
>>> print '{: d}'.format(-42)
-42
>>> print '% d' % (42)
42
>>> print '{: d}'.format(42)
42
>>> print '{:=5d}'.format((-42))
- 42
2.Dict类型的格式化输出
根据key取value:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> print '%(Sjoerd)d %(Jack)d %(Dcab)d' % table
4127 4098 7678
>>> print '{Sjoerd} {Jack} {Dcab}'.format(**table)
4127 4098 7678
>>> print '{t[Sjoerd]} {t[Jack]} {t[Dcab]}'.format(t=table)
4127 4098 7678
Dict遍历:
>>> for name, ID in table.items():
print '{0:10} ==> {1:10d}'.format(name,ID)
Dcab ==> 7678
Jack ==> 4098
Sjoerd ==> 4127
>>> for name, ID in table.items():
print '{1:<10d} ==> {0:>10}'.format(name,ID)
7678 ==> Dcab
4098 ==> Jack
4127 ==> Sjoerd
List 取值:
>>> table2 = ["Sjoerd","Jack","Dcab"]
>>> print '{t[0]} {t[2]}'.format(t=table2)
Sjoerd Dcab
3.输出对象的属性值
>>> class Plant(object):
type = 'tree'
kinds = [{'name':'oak'},{'name':'maple'}]
>>> print '{p.type}: {p.kinds[0][name]}'.format(p=Plant())
tree: oak
4.Datetime
>>> from datetime import datetime
>>> dt = datetime(2001, 2, 3, 4, 5)
>>> print '{:%Y-%m-%d %H:%M}'.format(dt)
2001-02-03 04:05
>>> print '{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
2001-02-03 04:05
5.参数化的格式
设置参数精度:
>>> print '%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)
Gib = 2.718
>>> print '{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
Gib = 2.718
参数位置:
>>> print '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
+2.72
6.重写format类
>>> class HAL9000(object):
def __format__(self, format):
if (format == 'open-the-pod-bay-doors'):
return "I'm afraid I can't do that."
return 'HAL 9000'
>>> print '{:open-the-pod-bay-doors}'.format(HAL9000())
I'm afraid I can't do that.