字符串格式化

1、打印浮点数%f

tp1="percent %.2f"%99.976234444444444444
print(tp1)

tp1="percent %.3f"%99.976234444444444444
print(tp1)

>>>

percent 99.98
percent 99.976

2、打印字符串%s,

      #字符串可接收数字,可接收浮点数

msg1 = 'my name is %s, my hobby is %s'   %('fu','pingpang')
msg2 = 'his name is %s'   %'zheng'
print(msg1)
print(msg2)

>>>

my name is fu, my hobby is pingpang
his name is zheng

3、打印数字型%d

msg1 = 'my name is %s, my age is %d'   %('fu',20)
print(msg1)

>>>my name is fu, my age is 20

4、打印百分号%%

tpl=' percent %.2f %%'     % 99.976234444
print(tpl)

>>>percent 99.98 %

5、按照键的方式打印

tpl="i am  %(name)s age %(age)d"    %{"name":"alex","age":18}
print(tpl)

>>>i am  alex age 18

 6、formatl格式化输出

 1 tpl="i am {}, age {},{}". format("seven",18,' alex')   # 一一对应,少一个即报错,如:
 2 #tpl="i am {}, age {},{}". format("seven",18)
 3 print(tpl)
 4 
 5 tp2 = "i am {2}, age {1},{0}".format("seven",18,'alex')   
 6 #通过索引传入值,在元组("seven",18,'alex') 中分别取第2个,第1个,第0个元素
 7 print(tp2)
 8 
 9 tp3 = "i am {0}, age {2},{0}".format("seven",18,'alex')   #通过索引传入值
10 print(tp3)
11 
12 tp4="i am {name}, age {age}, really {name}".format(name="seven", age=18)   #通过字典key取值
13 tp5="i am {name}, age {age}, really {name}".format(**{"name":"seven", "age":18})  #字典索引的另一种形式
14 print(tp4)
15 print(tp5)

tp1="i am {:s}, age{:d}".format(*["seven",18])  #列表索引
print(tp1)

 

posted @ 2020-01-27 10:08  卡子  阅读(150)  评论(0编辑  收藏  举报