python格式化输入包含'%'调用,及format方法
使用‘%’进行格式化输出
1 #最简单的字符串传参
2 tpl=
'i am %s '%
'alex'
3 >>>
i am alex
4
5 #字符串与整数传参
6 tpl =
'i am %s age %d'%(
'alex',18
)
7 >>>i am alex age 18
8
9 #字典的传参
10 tpl =
'i am %(name)s age %(age)d'%{
'name':
'alex',
'age':18
}
11 >>>i am alex age 18
12
13 #浮点型传参
14 tpl =
'percent %.2f'%99.97623
15 >>>percent 99.98
16
17 #字典中的浮点调用
18 tpl =
'i am %(pp).2f'%{
'pp':123.42556
}
19 >>>i am 123.43
20
21 #注意点:表示百分号的时候需要加个%
22 tpl =
'i am %.2f %%'%123.425556
23 >>>i am 123.43 %
24
25 #错误的方式
26 tpl =
'i am %.2f %'%123.425556
27 >>> tpl =
'i am %.2f %'%123.425556
28 >>>ValueError: incomplete format
format方法格式化输入
1 #format方法顺序对应传参
2 tpl =
'i am {},age{},{}'.format(
'serven',18,
'alex')
3 >>>
i am serven,age18,alex
4
5 #format列表传参*号为将列表分割后顺序传入,不加则会将整个传入而报错
6 tpl =
'i am {},age{},{}'.format(*[
'serven',18,
'alex'])
7 >>>
i am serven,age18,alex
8
9 #format标序传参
10 tpl =
'i am {0},age {1},really {0}'.format(
'serven',18
)
11 >>>i am serven,age 18
,really serven
12
13 #format指定参数名传参
14 tpl =
'i am {name},age {age},really {name}'.format(name=
'seven',age=18
)
15 >>>i am seven,age 18
,really seven
16
17 #format标序后指定下标传参
18 tpl =
'i am {0[0]},age{0[1]},really{0[2]}'.format([1,2,3],[11,22,33
])
19 >>>i am 1
,age2,really3
20
21 #对应顺序传参,f整数转为浮点型小数点后保留6位
22 tpl =
'i am {:s},age{:d},money {:f}'.format(
'seven',18,88888.1
)
23 >>>i am seven,age18,money 88888.100000
24
25 #format 字典传参
26 tpl =
'i am {name:s},age{age:d}'.format(**{
'name':
'seven',
'age':18
})
27 >>>
i am seven,age18
28
29 #:b转化为2进制,:o转化为8进制:x转化为16进制小写,:X转化为16进制大写:%将值转化为百分比
30 tpl =
'numbers : {:b},{:o},{:d},{:x},{:X},{:%}'.format(15,15,15,15,15,15.87623,2
)
31 >>>numbers : 1111,15,15,f,F,1587.623000%
转载于:https://www.cnblogs.com/liguangxu/p/5565438.html