format函数常与print()函数结合使用,具备很强的格式化输出能力。
1. 通过变量,逗号隔开:
print('{我}今天{action}'.format(我='脚踏前路',action ='在写博客')) # 通过关键字
输出:
2. 使用字典传入,在字典前加入**
grade = {'I' : '脚踏前路', '状态': '写博客'}
print('{I}在图书馆,{状态}'.format(**grade))#字典前加上**
输出:
3. 通过位置:
print('{0}今天{1}'.format('脚踏前路','写博客')) #通过位置
输出:
4. 文字排版:
print('{:^20}'.format('脚踏前路'))#居中 :^ 宽度14
print('{:>20}'.format('脚踏前路'))# 右对齐 :> 宽度14
print('{:<20}'.format('脚踏前路')) # 左对齐 :< 宽度14
print('{:*<20}'.format('脚踏前路')) # :后边可跟填充物,只允许一个字符
print('{:*>20}'.format('脚踏前路'))
输出:
5. 精度问题:
print('{:.1f}'.format(3.1415926))
print('{:.4f}'.format(3.14))# .后接保留小数点位数
输出:
6. 进制转换:
print('{:b}'.format(256)) # 十进制转换成二进制2
print('{:o}'.format(256)) # 十进制 转换成八进制8
print('{:d}'.format(256)) # 十进制 转换成十进制10
print('{:x}'.format(256)) # 十进制 转换成十六进制16
输出:
7. 千位分割符:
print('{:,}'.format(100000000))
print('{:,}'.format(235445.234235)) # 只对数字生效
输出: