4、format的三种玩法
# format格式化输出4.1) 自定义关键字匹配
res ='my name is {name},my age is {age}'.format(age=18, name='zxl')print(res)# 输出结果 my name is zxl,my age is 184.2) 按照索引匹配(默认和%s占位符一样,一一对应)
res1 ='my name is {},my age is {}'.format(18,'zxl')print(res1)# 输出结果 my name is 18,my age is zxl
res2 ='my name is {1},my age is {0}'.format(18,'zxl')print(res2)# 输出结果 my name is zxl,my age is 18
res3 ='my name is {1}{1}{1},my age is {0}{1}'.format(18,'zxl')print(res3)# 输出结果 my name is zxlzxlzxl,my age is 18zxl4.3)format高级玩法,对齐填充(<左对齐,>右对齐,^居中)
res1 ="my name is {1:*<10} my age is {0}".format(18,"zxl")
res2 ="my name is {1:*>10} my age is {0}".format(18,"zxl")
res3 ="my name is {1:*^10} my age is {0:=^10}".format(18,"zxl")print(res1)# 输出结果 my name is zxl*******,my age is 18print(res2)# 输出结果 my name is *******zxl,my age is 18print(res3)# 输出结果 my name is ***zxl****,my age is ====18====4.4) 进制与精度
res1 ="my name is {1:=^10} my age is {0:b}".format(18,"zxl")# b二进制
res2 ="my name is {1:=^10} my age is {0:o}".format(18,"zxl")# o八进制
res3 ="my name is {1:=^10} my age is {0:x}".format(18,"zxl")# x十六进制
res4 ="my name is {1:=^10} my salary is {0:,}".format(13333333333338,"zxl")
res5 ="my name is {1:=^10} my age is {0:.3f}".format(3.7777,"zxl")# 会四舍五入print(res1)# 输出结果 my name is ===zxl====,my age is 10010print(res2)# 输出结果 my name is ===zxl====,my age is 22print(res3)# 输出结果 my name is ===zxl====,my age is 12print(res4)# 输出结果 my name is ===zxl====,my salary is 13,333,333,333,338print(res5)# 输出结果 my name is ===zxl====,my age is 3.7784.5)*传入列表值,**传入字典的key和value
l1 =[18,'zxl','male']# 还是按照索引传值的,要保证列表有足够的值,否则报错
res1 ='my name is {},my age is {}'.format(*l1)print(res1)# 输出结果 my name is 18,my age is zxl
res2 ='my name is {1},my age is {0}'.format(*l1)print(res2)# 输出结果 my name is zxl,my age is 18
d1 ={'name':'zxl','age':18,'gender':'male'}# 按照key位置传值
res1 ='my name is {name},my age is {age}'.format(**d1)print(res1)# 输出结果 my name is zxl,my age is 18
res2 ='my name is {gender},my age is {age}'.format(**d1)print(res2)# 输出结果 my name is male,my age is 18# 错误使用示范
info={"age":18,"name":"egon"}
res="my name is {} my age is {}".format(*info)# 一个*,则只能传入keyprint(res)# 输出结果 my name is age,my age is name4.6) f""
name ="zxl"
age =18
res = f"my name is {name},my age is {age}"print(res)# 输出结果 my name is zxl,my age is 18