• 手机站
  • 收藏
聚培教育网合作机构 > 潍坊达内教育
潍坊达内教育
400-998-6158
潍坊达内教育育是一家由留学海归创办的高端职业教育培训机构,是中国人才培养平台、人才输送平台。
潍坊达内教育

Python中调用format函数进行字符串格式化

python学习网

更新时间:2021-11-02 浏览:73
核心提示:Python中调用format函数进行字符串格式化

一种常见字符串数组恢复出厂设置的方式 ,便是启用format()

>>> template='{0},{1} and {2}'

>>> template.format ('a','b','c')

'a,b and c'

>>> template='{name1},{name2} and {name3}'

>>> template.format (name1='a',name2='b',name3='c') 'a,b and c'

>>> template='{name1},{0} and {name2}'

>>> template.format ('a',name1='b',name2='c') 'b,a and c'

>>>

这儿依据以上的事例表明一下

1.更换的地段能够应用下标底来标识

2.更换的地段能够应用名字来更换

下边大家而言说,在方式 里边加上特性


>>>import sys

>>> 'my {1[spam]} runs {0.platform}'.format(sys,{'spam': 'laptop'}) 'my laptop runs win32'

>>>

>>> 'my {config[spam]} runs {sys.platform}'.format(sys=sys,config={'spam':'laptop'}) 'my laptop runs win32'

>>>

上边2个事例里边,**处载入了字符串数组,第二处载入sys里边的platform特性

下边再举一个事例,表明在关系式里边应用偏移


>>> aList=list('abcde')

>>> aList ['a', 'b', 'c', 'd', 'e']

>>> 'first={0[0]} third={0[2]}'.format (aList) 'first=a third=c'

>>>

留意:在应用偏移的情况下只可以是整数,不能够应用负值,不能够应用意味着区段整数


>>> aList=list('abcde')

>>> aList ['a', 'b', 'c', 'd', 'e']

>>> 'first={0[0]} third={0[-1]}'.format (aList)

Traceback (most recent call last):

File "", line 1, in

'first={0[0]} third={0[-1]}'.format (aList)

TypeError: list indices must be integers, not str

>>> 'first={0[0]} third={0[1:3]}'.format (aList) Traceback (most recent call last):

File "", line 1, in

'first={0[0]} third={0[1:3]}'.format (aList)

TypeError: list indices must be integers, not str

>>>
更多>同类资讯
更多>相关课程
顶部