1.百分号
格式如下:
%[(name)] [flags] [.precision] typecode
(name):可选,获取指定key的值
flags:可选,:width,占有宽度
.precision:可选,小数点后保留位数
typecode:必选
1)s,传入对象的__str__方法的返回值
2)c,整数
3)o,整数转八进制
4)d,整数转十进制
5)e,整数,浮点数转科学计数法
6)f,整数,浮点数转浮点数
7)F,整数,浮点数转浮点数
8)g,自动调整将整数,浮点数转浮点型或科学计数法
9)G,自动调整将整数,浮点数转浮点型或科学计数法
10)%,%%表示一个百分号
2.使用示例
result1 = "i am %s" % ‘shijingjing07‘ result2 = "i am %s, score: %d" % (‘shijingjing07‘,100) result3 = "i am %(name)s, score: %(age)d" % ({‘name‘:‘shijingjing07‘,‘age‘:100}) result4 = "%.2f" % 99.333 result5 = "%.2f%%" % 99.333 print(result1) print(result2) print(result3) print(result4) print(result5)
运行结果:
3.format方式
result1 = ‘I am {},age {},{}‘.format(‘shijingjing‘,2,‘hello‘) result2 = ‘I am {},age {},{}‘.format(*[‘shijingjing‘,2,‘hello‘]) result3 = ‘I am {0},age {1},{0}‘.format(‘shijingjing‘,2) result4 = ‘I am {0},age {1},{0}‘.format(*[‘shijingjing‘,2]) result5 = ‘I am {name},age {age},{name}‘.format(**{‘name‘:‘shijingjing‘,‘age‘:18}) result6 = ‘I am {name},age {age},{name}‘.format(name=‘shijingjing‘,age=18) result7 = ‘I am {0[0]},age {0[1]},{0[2]}‘.format([1,2,3],[4,5,6]) result8 = ‘I am {:s},age{:d}‘.format(‘shijingjing‘,2) result8 = ‘I am {name:s},age{age:d}‘.format(name=‘shijingjing‘,age=2) result9 = ‘numbers: {:b},{:o},{:d},{:x},{:X},{:%}‘.format(15,15,15,15,15,15.87623) result10 = ‘numbers: {0:b},{0:o},{0:d},{0:x},{0:X},{0:%}‘.format(15) result11 = ‘numbers: {num:b},{num:o},{num:d},{num:x},{num:X},{num:%}‘.format(num=15) print(result1) print(result2) print(result3) print(result4) print(result5) print(result6) print(result7) print(result8) print(result9) print(result10) print(result11)
运行结果:
时间: 2024-10-19 03:41:52