标签:precision percent 相对 mat 空格 fill 十六进制 div 返回值
引用:http://www.cnblogs.com/wupeiqi/articles/5484747.html
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
1、百分号方式
%[(name)][flags][width].[precision]typecode
注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式
常用格式化:
1 tpl = "i am %s" % "alex" 2 3 tpl = "i am %s age %d" % ("alex", 18) 4 5 tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} 6 7 tpl = "percent %.2f" % 99.97623 8 9 tpl = "i am %(pp).2f" % {"pp": 123.425556, } 10 11 tpl = "i am %.2f %%" % {"pp": 123.425556, }
2、Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
常用格式化:
1 tpl = "i am {} age {} {}".format("seven", 18, ‘alex‘) 2 #结果:i am seven age 18 alex 3 tpl = "i am {}, age {}, {}".format(*["seven", 18, ‘alex‘]) 4 #结果:i am seven, age 18, alex 5 tpl = "i am {0}, age {1}, really {0}".format("seven", 18) 6 #结果:i am seven, age 18, really seven 7 tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18]) 8 #结果:i am seven, age 18, really seven 9 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) 10 #结果:i am seven, age 18, really seven 11 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) 12 #结果:i am seven, age 18, really seven 13 tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) 14 #结果:i am 1, age 2, really 3 15 tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) 16 #结果:i am seven, age 18, money 88888.100000 17 tpl = "i am {:s}, age {:d}".format(*["seven", 18]) 18 #结果:i am seven, age 18 19 tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18) 20 #结果:i am seven, age 18 21 tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) 22 #结果:i am seven, age 18 23 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 24 #结果:numbers: 1111,17,15,f,F, 1587.623000% 25 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 26 #结果:numbers: 1111,17,15,f,F, 1587.623000% 27 tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) 28 #结果:numbers: 1111,17,15,f,F, 1500.000000% 29 tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15) 30 #结果:numbers: 1111,17,15,f,F, 1500.000000% 31 print(tpl)
标签:precision percent 相对 mat 空格 fill 十六进制 div 返回值
原文地址:https://www.cnblogs.com/dsynb/p/9100360.html