更多课程 选择中心


Python培训

400-111-8989

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

  • 发布:Python培训
  • 来源:Python知识大全
  • 时间:2019-09-20 11:28

一种常用字符串格式化的方法,就是调用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'

>>>

上面两个例子里面,第一处读取了字符串,第二处读取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

>>>

免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

预约申请免费试听课

填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:Python format的用法
下一篇:Python 浮点数的冷知识

2021年Python全套免费视频教程在哪里?

Python编程学习路线

Python最高有几级?

人工智能与语音遥控的区别?

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

Copyright © 2023 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省