字符串格式化

it2024-12-08  19

1.%s可以接收一切类型的传值 msg ='i am %s my hobby is %s '% ('lhf','alex') #接收 字符串 print(msg)

2.接收 列表  、接收 集合 

msg ='i am %s my hobby is %s '% ('lhf',[1,2])#接收 列表 print(msg) msg ='i am %s my hobby is %s '% ('lhf',{1,2})#接收 集合 print(msg)

3.%d 只能接收数字

name = 'lhf' age = 19 msg ='i am %s my hobby is %d '% (name,age) #传过来的值一般都是变量,所以我们在使用百分号s时,要注意代码的可读性 print(msg) # msg ='i am %s my hobby is %d '% ('lhf',1213)

4.%.2f 打印浮点数 且只保留小数点后两位数 

# %.2f 打印浮点数 且只保留小数点后两位数 tpl = "percent %.2f" % 99.976221212123 print(tpl) # 打印百分比 tpl = 'percent %.2f %%'% 99.976221212123 print(tpl) # 通过字典的键值对来传值 tpl = "i am %(name)s age %(age)d" % {"name":"alex","age":18} print(tpl)

 

转载于:https://www.cnblogs.com/renzhiqiang/p/10861518.html

最新回复(0)