承接上一章节。我们这一节来说说字符串格式化的还有一种方法。就是调用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 "<pyshell#2>", line 1, in <module>
'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 "<pyshell#3>", line 1, in <module>
'first={0[0]} third={0[1:3]}'.format (aList)
TypeError: list indices must be integers, not str
>>>

就讲到这里,谢谢大家

------------------------------------------------------------------

点击跳转零基础学python-文件夹

最新文章

  1. ObjectAnimator属性动画应用demo
  2. Python学习之路
  3. 【mysql中myisam和innodb的区别】
  4. 常见的几种RuntimeException
  5. Plugin with id 'com.android.application' not found.
  6. C#部署安装,将用户安装路径记录下写入注册表,并启动
  7. VCS仿真 Dump Memory
  8. avalon1.5+中组件的定义方式
  9. Servlet中 End event threw exception,错误404 的解决方法
  10. python 工具安装
  11. HTML之body标签中的相关标签
  12. Eclipse启动报错,解决办法
  13. nginx实现动态/静态文件缓存(week4_day1_part2)-技术流ken
  14. WineBottler for Mac(Mac 运行 exe 程序工具)安装
  15. 20155201 网络攻防技术 实验九 Web安全基础
  16. Mac Python PyQt5 环境搭建
  17. PHP:第一章——PHP中逻辑运算符的使用方法
  18. 微信公众号开发笔记1(nodejs开发)
  19. mysql中innodb和myisam的区别
  20. ubuntu 下安装 jdk

热门文章

  1. poj1028--动态规划--Ignatius and the Princess III
  2. React-Native Android开发沉思录
  3. 【BZOJ1196】【HNOI2006】公路修建问题
  4. 前端分页功能实现(PC)
  5. Python笔记(九)
  6. guice 整合ninja framework(七)
  7. C#监测方法执行效率
  8. 目标跟踪ObjectT综述介绍
  9. 04--深入探讨C++中的引用
  10. 通过nvm 切换 npm 版本