2.实例
(1)不设置位置,按默认顺序(从左到右)输出。
#默认顺序
'学习{}中的{}函数'.format('python','format')
->'学习python中的format函数'
(2)指定位置
#指定顺序
'学习{1}中的{0}函数'.format('format','python')
->'学习python中的format函数'
(3)设置参数
#1⃣️
list1 = ['hello','say','world','s']
print('LiMing {0[1]}{0[3]} {0[0]} to {0[2]}'.format(list1))
#输出:LiMing says hello to world
#②
list1 = ['hello','say']
list2 = ['world','s']
print('LiMing {0[1]}{1[1]} {0[0]} to {1[0]}'.format(list1,list2))
#输出:LiMing says hello to world
说明:传入的参数中指定位置“0[1]”表示list1这个参数,0表示第一个参数即list1,而0[1]中的1是表示list1中的第二个位置的值。‘1[0]’是表示第二个参数list2的第一个值。
(4)数字格式化
# 保留两位小数点
print('{:.2f}'.format(314.541))
#314.54
# 保留一位小数点并携带正负符号
print('{:+.1f}'.format(1.2684))
#=1.3
print('{:+.1f}'.format(-45.62556))
#-45.6
# 不保留小数点
print('{:.0f}'.format(-45.62556))
#-46
②百分比格式
#保留两位小数点的百分比
print('{:.2%}'.format(0.54036))
#54.04%
# 不保留小数点的百分比
print('{:.0%}'.format(0.54036))
#54%
③转进制
# b二进制,>右对齐,长度为20
print('{:>20b}'.format(23))
# 10111
# d十进制,<左对齐,长度为15
print('{:_<15d}'.format(892))
#892____________
# x十六进制,^居中对齐,长度为10
print('{:_^10x}'.format(16894))
#___41fe___
# o八进制,^居中对齐,长度为10
print('{:_^10o}'.format(1394))
#___2562___
因篇幅问题不能全部显示,请点此查看更多更全内容