经过位置参数传参html
print('{}, {}'.format('KeithTt', 18)) # KeithTt, 18
位置参数能够经过索引调用python
print('{1}, {0}'.format('KeithTt', 18)) # 18, KeithTt
经过关键字参数传参code
print('{name}, {age}'.format(name='KeithTt', age=18)) # KeithTt, 18 print('{age}, {name}'.format(name='KeithTt', age=18)) # 18, KeithTt
^, <, > 分别是居中、左对齐、右对齐,后面带宽度
: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充
+ 表示老是显示正负符号,在正数前显示 +,负数前显示 -
b、d、o、x 分别是二进制、十进制、八进制、十六进制orm
保留两位小数,其中.2表示精度,f 表示float类型htm
print('{:.2f}'.format(3.1415926)) # 3.14 >>> print('{:.5f}'.format(3.1415926)) # 3.14159
不带类型时比较特殊,使用科学计数法,若是整数位个数+1大于精度,将使用符号表示对象
>>> print('{:.2}'.format(3.1415926)) # 3.1 >>> print('{:.2}'.format(13.1415926)) # 1.3e+01 >>> print('{:.3}'.format(13.1415926)) # 13.1
不带小数,即精度为0索引
print('{:.0f}'.format(3.1415926)) # 3
加号 + 表示老是输出正负符号ip
print('{:+.2f}'.format(3.1415926)) # +3.14 print('{:+.2f}'.format(-3.1415926)) # -3.14
指定宽度和对齐方式,默认是右对齐>,>符号可省ci
print('{:>10.2f}'.format(3.1415926)) # 3.14 print('{:<10.2f}'.format(3.1415926)) # 3.14 print('{:^10.2f}'.format(3.1415926)) # 3.14
指定填充字符,默认是空格,只能是一个字符字符串
print('{:0>10.2f}'.format(3.1415926)) # 0000003.14 print('{:*>10.2f}'.format(3.1415926)) # ******3.14 print('{:*<10.2f}'.format(3.1415926)) # 3.14******
用等号 = 让正负符号单独在最前面
print('{:=+10.2f}'.format(3.1415926)) # + 3.14 print('{:=+10.2f}'.format(-3.1415926)) # - 3.14
加上填充字符,正负符号始终在最前面
print('{:*=+10.2f}'.format(3.1415926)) # +*****3.14 print('{:0=+10.2f}'.format(3.1415926)) # +000003.14
用逗号分隔数字
print('{:,}'.format(1000000)) # 1,000,000
将浮点数转换成百分比格式
print('{:.0%}'.format(0.25)) # 25%
使用大括号 {} 转义大括号
print ('{}对应的位置是{{0}}'.format('KeithTt')) # KeithTt对应的位置是{0}
另外,除了format()以外,字符串对象还有一些其它更直观的格式化方法
示例: 格式化打印下面的数据,要求各部分对齐
d = { 'lodDisk': 100.0, 'SmallCull': 0.04, 'DistCull': 500.0, 'trilinear': 40, 'farclip': 477 } # 计算出全部key的最长宽度 w = max(map(len, d.keys())) print(w) # 9 for k,v in d.items(): print(k.ljust(w), ':', v)
lodDisk : 100.0 SmallCull : 0.04 DistCull : 500.0 trilinear : 40 farclip : 477
参考:
https://docs.python.org/3/library/functions.html#format
https://docs.python.org/3/library/string.html#format-specification-mini-language
http://docspy3zh.readthedocs.io/en/latest/tutorial/inputoutput.html
http://www.runoob.com/python/att-string-format.html