#对于每一个大括号,在后面的参数中找到对应的参数插进来#format操作类似于于将传入的参数制成多个数据的数据结构元组或者字典,然后依照索引插入参数
s ="i am {},i am {} years old ,i like {}".format("haiyang",20,"zhu")print(s)
s ="i am {},i am {} years old ,i like {}".format("haiyang","20","zhu")print(s)
i am haiyang,i am 20 years old ,i like zhu
i am haiyang,i am 20 years old ,i like zhu
2,定义变量的索引
s ="i am {2},i am {1} years old ,i like {0}".format("haiyang",20,"zhu")print(s)
i am zhu,i am 20 years old ,i like haiyang
3,定义变量名称
#类似于索引,只不过这里的索引变成了自定义的索引,不再是0-...因此需要传入字典
s ="i am {name},i am {age} years old ,i like {girl}".format(name="haiyang",age=20,girl="zhu")print(s)
i am haiyang,i am 20 years old ,i like zhu
4,控制输出长度和格式
s ="i am {:.2s},i am {:d} years old ,i like {:.2f}".format("haiyang",20,22.231231321)print(s)
tmp =("haiyang",20,"zhu")
s ="i am {},i am {} years old ,i like {}".format(*tmp)print(s)
s ="i am {},i am {} years old ,i like {}".format(tmp)print(s)
i am haiyang,i am 20 years old ,i like zhu
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-5-bfc251778bb3> in <module>()
4 s = "i am {},i am {} years old ,i like {}".format(*tmp)
5 print(s)
----> 6 s = "i am {},i am {} years old ,i like {}".format(tmp)
7 print(s)
IndexError: tuple index out of range
如果需要传入字典而你已经把字典做好了,就需要用**标识一下,否则也会报错
dic ={"name":"haiyang","age":20,"girl":"zhu"}
s ="i am {name},i am {age} years old ,i like {girl}".format(**dic)print(s)
s ="i am {name},i am {age} years old ,i like {girl}".format(dic)print(s)
i am haiyang,i am 20 years old ,i like zhu
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-9-ffa4c40a411c> in <module>()
3 s = "i am {name},i am {age} years old ,i like {girl}".format(**dic)
4 print(s)
----> 5 s = "i am {name},i am {age} years old ,i like {girl}".format(dic)
6 print(s)
KeyError: 'name'