一般框架
tplt = '' #格式化模板 print(tplt.format(…)) #填充内容 tplt = '{0}-{1}+{2}={3}' {}表示了一个槽,槽里面的内容使用key:value表示,key取值为自然数,表示序号,与后面format()的参数列表对应,value设置槽的格式,可由以下属性组合: 字符 用于填充单个字符 < 左对齐 > 右对齐 ^ 居中对齐 数字 槽的宽度 , 数字的千位分隔符 .数字 浮点小数的精度或字符串的最大输出长度 类型 整型b,c,d,o,x,X,浮点型e,E,f,% format('a', 'b','c','d'),'a'填充到槽1内,'b'填充到槽2内,'c'填充到槽3内,'d'填充到槽4内
例1 输出pi的逼近值
# -*- coding=utf-8 -*- import math import sys from decimal import * # bailey-borwein-plouffe formula calculating pi def bbp(n): pi=Decimal(0) k=0 while k < n: pi+=(Decimal(1)/(16**k))*((Decimal(4)/(8*k+1))-(Decimal(2)/(8*k+4))-(Decimal(1)/(8*k+5))-(Decimal(1)/(8*k+6))) k+=1 return pi if __name__ == '__main__': tplt = '{0:^10}{1:<30f}' print('{0:^10}{1:^30}'.format('n','pi')) for i in range(1,10): print(tplt.format('n='+str(i**2), bbp(i**2)))
结果如下:
kang@USTC:~/workspace/python_spyder$ python3 test_format_print.py n pi n=1 3.133333333333333333333333333 n=4 3.141592457567435381837004555 n=9 3.141592653589752275236177867 n=16 3.141592653589793238462593174 n=25 3.141592653589793238462643381 n=36 3.141592653589793238462643381 n=49 3.141592653589793238462643381 n=64 3.141592653589793238462643381 n=81 3.141592653589793238462643381
例2 测试字符填充
>>> tplt = '{1:{2}^5}---{0}' >>> print(tplt.format('0', '1', '*')) **1**---0 >>> tplt = '{1:{2}<5}---{0}' >>> print(tplt.format('0', '1', '*')) 1****---0 >>> tplt = '{1:{2}>5}---{0}' >>> print(tplt.format('0', '1', '*')) ****1---0 >>> tplt = '{1:{2}^6}---{0}' >>> print(tplt.format('0', '1', '*')) **1***---0