字符串格式化有两种
①%
②format
一、%
%s 可代替所有类型,%d只能接数字
msg = 'i am %s, i like %s' % ('mingming', 2) print(msg) msg = 'i am %s, i like %s' % ('mingming', [1,2]) print(msg)
%(.n)f打印浮点数,默认n=6
print('num=%f' % 99.1234567890) print('num=%.3f' % 99.1234567890)
%(.n)f%%打印百分数(四舍五入)
print('num=%.2f%%' % 99.1294567890)
%(xxx)s %({'xxx':value)以字典方式格式化(无先后顺序)
print('i am %(name)s i am %(age)s' % ({'age': 18, 'name': 'jiangzhch'}))
二、format
1、一一对应传值,不一一对应则报错
tpl = "i am {}, age {}".format("seven", 18) print(tpl)
2、以数字(索引)站位传值,format括号内value可以不全都用
tpl = "i am {2}, age {1}, really {0}".format("seven", 18, 'silly') print(tpl)
tpl = "i am {2}, age {1}".format("seven", 18, 'silly') print(tpl)
3、以字典形式传值,必须加**
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
4、列表传值时要加*
l=["seven", 18] tpl = "i am {:s}, age {:d}".format(*l)
5、:
''' b--转化成二进制 o--转化成八进制 d--转化成十进制 x--转化成十六进制(小写) X--转化成十六进制(大写) %--转化成百分比(保留小数点后六位) ''' tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(15, 15, 15, 15, 15, 15.87623, 2)