百分号方式
1.(1) %s 传递字符串、列表等等 (%.ns 截取传入字符串的前n位传入)
dmsg = ' i am %s ,my hobby is %s' %('jiao','basketball')
print(msg)
运行结果: i am jiao ,my hobby is basketball
(2)%d 传递数字,其他数据类型不行
2.打印浮点数 %.(n)f 通过设置n来确定保留几位,
tpl = 'percent %.5f' % 1.66564848123135 print(tpl)
运行结果:percent 1.66565
3.打印百分比 %%
tpl = '%.5f %%' %1.66564848123135
print(tpl)
运行结果:1.66565 %
4.用键值对进行拼接
msg = 'i am %(name)s ,i am %(age)d years old' % {'name':'jiao ','age':18 }
print(msg)
运行结果:i am jiao ,i am 18 years old
5.拼接
print('j','i','a','o',sep='_')
运行结果:j_i_a_o
format方式
1.传值,
(1)必须是一一对应,否则将会报错
msg = 'i am {} ,my age is {}'.format('jiao',18) print(msg)
运行结果:i am jiao ,my age is 18
(2)可以通过在大括号中添加序号的方式
msg = 'i am {1} ,my age is {0},my hobby is {2}'.format('jiao',18,'basketball')
print(msg)
运行结果:i am 18 ,my age is jiao,my hobby is basketball
还可以:tpl = ' i am {0[0]},age{0[0]},really {1[2]}'.format([1,2,3],[11,22,33])
(3)设置名称进行传值 ,format口括号内顺序无要求
msg = 'i am {name} ,my age is {age},my hobby is {hobby}'.format(age=18,name='jiao',hobby='basketball')
print(msg)
运行结果:i am jiao ,my age is 18,my hobby is basketball