day 14 字符串格式化
%s ,传递任何参数,例如:字符串,数字,列表等:
name = "my name is %s age is %s."%('hsf',29) print(name)
%d: 只能传递数字参数
%f :传递浮点数(默认保留小数点后6位,可以指定保留位数)
num = ('percent %f'%(3.1415926)) print(num) #输出===>percent 3.141593 num1 = ('percent %.2f'%(3.1415926)) #指定保留两位 print(num1) #输出===>percent 3.14
浮点数打印%
num = ('percent %f%%'%(3.1415926)) print(num) #输出===>percent 3.141593%
通过键来传递参数:
name = "my name is %(name)s age is %(age)s."% {"name":"hsf","age":29} print(name) #输出===>my name is hsf age is 29.
format字符串格式化
常用格式化:
1 . 通过位置传参:
name = "my name is {} , age is {} ,my dog name is {}".format("hsf",29,"ez") print(name)
2.通过下标方式传参:
name = "my name is {1} , age is {0} ,my dog name is {2}".format("hsf",29,"ez") print(name)
3.以字典的形式传参:format(**())
name = "my name is {name} , age is {age} ,my dog name is {dog}".format(name = "hsf",age=29,dog = "ez") print(name) #输出===>my name is hsf , age is 29 ,my dog name is ez name = "my name is {name} , age is {age} ,my dog name is {dog}".format(**{"name":"hsf","age":29,"dog":"ez"}) print(name) #输出===>my name is hsf , age is 29 ,my dog name is ez
4.通过索引的元组方式传参:
name = "my name is {0[1]} , age is {0[2]} ,my dog name is {1[1]}".format([1,2,3],[4,5,6]) print(name) #输出===>my name is 2 , age is 3 ,my dog name is 5
5. 列表的形式传参:format(*())
6.多种形式传参:
---:b>>>以二进制形式传入
---:o>>>以八进制形式传入
---:d>>>以整型的形式传入
---:x>>>以十六进制形式传入(小写的十六进制)
---X>>>以十六进制形式传入(大写的十六进制)
---:%>>>打印百分比
numbers = "numbers:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.87623) print(numbers) 输出===>numbers:1111,17,15,f,F,1587.623000%