字符串格式化:
【1】%s: (%s实际上什么都可以传)
1 a='I am %s and my hobby is python' %'zy' 2 print(a) 3 #运行结果:I am zy and my hobby is python 4 a='I am %s and my hobby is %s' % ('zy','python') 5 print(a) 6 #运行结果:I am zy and my hobby is python 7 a='I am %s and my hobby is %s' % ('zy',520) #%s实际上是万能的 8 print(a) 9 #运行结果:I am zy and my hobby is 520 10 a='I am %s and my hobby is %s' % ('zy',[5,2,0]) 11 print(a) 12 #运行结果:I am zy and my hobby is [5,2,0]
【2】%d: (只能传整数)
1 b='I am %s my hobby is %d' % ('zy',520) 2 print(b) 3 #运行结果:I am zy my hobby is 520
【3】%f:
1 c='I have %.2f money' % 100.23456 2 print(c) 3 #运行结果:I have 100.23 money
1 打印百分比: 2 d='I have %.2f%% money' % 88.8888 3 print(d) 4 #运行结果:I have 88.89% money (自动四舍五入)
【4】字典传值格式化
1 e="I am %(name)s age %(age)d" %{"name":"zy","age":18} 2 print(e) 3 #运行结果:I am zy age 18
【5】format字符串格式化
1 a="I am {},age {},{}".format("seven",20,"zy") 2 print(a) 3 #运行结果:I am seven,age 20,zy 4 5 b="I am {2},age {1}, {0}".format("seven",18,"zy") #索引 6 print(b) 7 #运行结果:I am zy,age 18, seven 8 9 c="I am {1},age {1}".format("seven",18,"zy") 10 print(c) 11 #运行结果:I am 18,age 18 12 13 d="I am {name}, age {age}, really {name}".format(name="zy",age=20) 14 print(d) #字典 15 #运行结果:I am zy, age 20, really zy 16 17 e="I am {name}, age {age}, really {name}".format(**{"name":"zy","age":18}) 18 print(e) #字典必须加两个**来传值 19 #运行结果:I am zy, age 18, really zy 20 21 f="I am {:s}, age {:d}, money {:f}".format("zy",20,"8888.88") 22 print(f) 23 #运行结果:I am zy, age 20, money 8888.880000 24 25 g="I am {:s},age {:d}".format(*["zy",20]) #一个*列表传值 26 print(g) 27 #运行结果:I am zy,age 20 28 29 h="number: {:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.66) 30 print(h) 31 #运行结果:number: 1111,17,15,f,F,1566.000000%