一、%字符串格式化
1、使用%s 后面一一对应输入的字符串,%s可以接受任何参数。
print("I am %s hobby is %s"%("lisi","wangwu"))
I am lisi hobby is wangwu
2、%d 只能接受数字
print("I am %s,age is %d"%("lisi",14))
I am lisi,age is 14
3、浮点格式化 %f(默认保留小数点后六位)
print("比值为%f"%15.343324123)
比值为15.343324
4、指定保留位数打印
print("比值为%.2f"%15.3433248585)
15.34
5、打印%号,需输入两个%号
print("比值为%.2f%%"%15.3433248585)
15.34%
6、使用键值对
print("%(tim1)s和%(tim2)s的比赛比分是%(s1)svs%(s2)s"%{"tim1":"火箭","tim2":"勇士","s1":98,"s2":94})
火箭和勇士的比赛比分是98vs94
7、+ 右对齐,-左对齐
tp1 = "I am %(name)+30s %(age)d" %{"name":"zhangsan","age":18}
print(tp1)
I am zhangsan 18
8、拼接
print("1","2","3",sep="_")
1_2_3
二、format字符串格式化
1、使用前后{ },后面必须一一对应
tp1 = "I am {},age is {}".format('zhangsan', 18)
print(tp1)
I am zhangsan,age is 18
2、{ }里面加入数字,0为索引开始的整数
tp1 = "I am {1},age is {0}".format('zhangsan', 18)
print(tp1)
I am 18,age is zhangsan
3、可以不一一对应索引,但索引必须存在。
tp1 = "I am {1},age is {1}".format('zhangsan', 18)
print(tp1)
I am 18,age is 18
4、使用字典形式
tp1 = "I am {name},age is {age}".format(name='zhangsan',age=14)
print(tp1)
I am zhangsan,age is 14
5、也可以使用**接一个字典
tp1 = "I am {name},age is {age}".format(**{"name":"kobe","age":18})
print(tp1)
I am kobe,age is 18
6、使用索引来对应值
tp1 = "I am {0[2]},age is {1[2]}".format([2,3,4,5],[1,2,3,4])
print(tp1)
I am 4,age is 3
7、使用 :s :d :f 的格式
tp1 = "I am {:s},age is {:d},money is{:f}".format("tom",16,18.434)
print(tp1)
I am tom,age is 16,money is18.434000
8、使用*加列表传递
tp1 = "I am {:s},age is {:d},money is{:f}".format(*["dhuwn",145,24.3434])
print(tp1)
I am dhuwn,age is 145,money is24.343400
9、数字格式b二进制 o八进制 d十进制 x小写16进制 X大写16进制 %转换成百分百默认保留小数后六位
tp1 = "number: {:b} {:o} {:d} {:x} {:X} {:%}".format(13,13,13,13,13,0.234234)
print(tp1)
number: 1101 15 13 d D 23.423400%