零基础学python-7.7 字符串格式化方法(1)
2017-06-02 10:33
330 查看
承接上一章节。我们这一节来说说字符串格式化的还有一种方法。就是调用format()
这里依据上面的样例说明一下
1.替换的位置能够使用下标的来标记
2.替换的位置能够使用名称来替换
以下我们来说说,在方法里面加入属性
上面两个样例里面。第一处读取了字符串,第二处读取sys里面的platform属性
以下再举一个样例,说明在表达式里面使用偏移量
注意:在使用偏移量的时候仅仅可以是正整数,不可以使用负数。不可以使用代表区间正整数
就讲到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-文件夹
>>> 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-文件夹
相关文章推荐
- 零基础学python-7.7 字符串格式化方法(1)
- 零基础学python-7.7 字符串格式化方法(1)
- 零基础学python-7.7 字符串格式化方法(2)
- 零基础学python-7.7 字符串格式化方法(2)
- 零基础学python-7.7 字符串格式化方法(1)
- 零基础学python-7.7 字符串格式化方法(2)
- Python中字符串的格式化方法小结
- Python实现字符串格式化的方法小结
- Python格式化字符串的四种方法
- python的三种字符串格式化方法
- python中格式化字符串的方法(字符串模板的应用)
- Python字符串格式化的方法(两种)
- Python3.x版本中新的字符串格式化方法
- Python字符串格式化输出方法分析
- Python实现字符串格式化输出的方法详解
- python字符串格式化方法 format函数的使用
- python 格式化字符串的三种方法
- Python格式化字符串的方法
- python中格式化字符串输出的方法总结
- Python 格式化字符串的三种方法