python学习笔记之基础操作(五)字符串格式化(2)format

format格式化

1,基本格式

#对于每一个大括号,在后面的参数中找到对应的参数插进来
#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)

i am ha,i am 20 years old ,i like 22.23

5,格式化传入数据的格式需求

在format等类似的函数中,会默认你传入的是一组数据,这是函数边长参数的相关知识
但是如果你直接将一组数据制成链表形式的数据格式传入,则需要通知,否则会将传入的列表当做一
个元素处理而不会去遍历列表中的元素
比如第一种,需要传入的数据类似于元组,如果想直接传入一个元组,则需要用*标识,否则会报错
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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值