一,%字符串格式化
1,使用%s 后面一一对应输入对应的字符串,%s可以接受任何参数
print ("I am %s hobby is zhangsan"%'lishi')
print ("I am %s hobby is %s"%('lishi','zhangsan'))
I am lishi hobby is zhangsan
I am lishi hobby is zhangsan
2,%d只能接受数字
msg = "I am %s my age is %d"%('lishi',18) print(msg) I am lishi my age is 18
3,浮点数格式化
tp1 = "percent %f" %99.97623 print(tp1) percent 99.976230
4,默认保留小数点后六位,指定保留位数打印
tp1 = "percent %.2f" %99.97623 print(tp1) percent 99.98
5,如果需要打印%输入两个%即可
tp1 = "percent %.2f%%" %99.97623 print(tp1) percent 99.98%
6,使用键值
tp1 = "I am %(name)s %(age)d" %{"name":"zhangsan","age":18} print(tp1) I am zhangsan 18
7,可选 + 右对齐 -左对齐 (用途少,还可以加颜色)
tp1 = "I am %(name)-30s %(age)d" %{"name":"zhangsan","age":18} print(tp1) I am zhangsan 18
9,拼接
print('1','2','3',sep=':') 1:2:3
二,format字符串格式化
前面使用{}后面必须一一对应
tp1 = "I am {},age is {}".format('zhangsan',18) print(tp1) I am zhangsan,age is 18
{}里面加入数字,数字取值为0开始的整数,按照索引取值
tp1 = "I am {1},age is {0}".format('zhangsan',18) print(tp1) I am 18,age is zhangsan
可以不一一对应但是索引值不能超过索引的位数
tp1 = "I am {1},age is {1}".format('zhangsan',18) print(tp1) I am 18,age is 18
使用字典形式
tp1 = "I am {name},age is {age}".format(name = 'zhangsan',age = 18) print(tp1) I am zhangsan,age is 18
也可以使用**接一个字典
tp1 = "I am {name},age is {age}".format(**{'name':'zhangsan',"age":18}) print(tp1) I am zhangsan,age is 18
使用索引
tp1 = "I am {0[0]},age {0[1]},really {0[2]}".format([1,2,3],[11,22,33]) print(tp1) I am 1,age 2,really 3
使用:s :d :f的格式
tp1 = "I am {:s},age {:d},money {:f}".format('zhangsan',18,888888.8) print(tp1) I am zhangsan,age 18,money 888888.800000
使用*加列表传递(必须要加*号)
tp1 = "I am {:s},age {:d}".format(*['zhansan',18]) print(tp1) I am zhansan,age 18
数字格式b二进制 o八进制 d十进制 x小写16进制 X大写16进制 %转换成百分百默认保留小数后六位
tp1 = "number: {:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.87623) print(tp1) number: 1111,17,15,f,F,1587.623000%