Python format函数使用总结

参考https://www.cnblogs.com/qunqun/p/8877924.html和https://www.cnblogs.com/Alexzzzz/p/6832253.html

1、位置参数

'{}+{}={}'.format(1,2,1+2)    
'{0}+{1}={2}'.format(1,2,1+2)
'{1}+{0}={2}'.format(1,2,1+2)
'{0}+{1}={1}'.format(0,1)
'my name is {} ,age {}'.format(*list0) (list0 = ['hcq'20]
"name is {0[0]} age is {0[1]}".format(list0)

2、关键字参数:
"my name is {name}, age {age}".format(name = "hcq", age = 20)
'my name is {name} ,age {age}'.format(**dict0) (dict0 = {'name''hcq''age'20}
3、填充与格式化

:[填充字符][对齐方式 <^>][宽度]
"{0:*>10}".format(10) "{0:*<10}".format(8) "{0:*^10}".format(3)
4、精度控制

"{0:.2}".format(10/3)  =3.3
"{0:.2f}".format(10/3) =3.33

"{0:.2%}".format(1/3)
"{:,}".format(123456798456)
"{0:b}".format(10)二进制、o|x八和十六进制

猜你喜欢

转载自www.cnblogs.com/figo-studypath/p/9243263.html