# 零基礎學python-7.7 字符串格式化方法(1)
承接上一章節,我們這一節來說說字符串格式化的另一種方法,就是調用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-7.1 python中的字符串簡介與常用函數
- 零基礎學python-7.2 字符串常量
- 零基礎學python-7.3 字符串的一般使用
- 零基礎學python-7.4 修改字符串實例總結
- 零基礎學python-7.5 文本解析
- 零基礎學python-7.6 字符串格式化表達式
- 零基礎學python-7.7 字符串格式化方法(1)
- 零基礎學python-7.7 字符串格式化方法(2)
- 輕松python文本專題-單獨處理字符串每個字符的方法匯總
- 輕松python文本專題-字符與字符值轉換
- 輕松python文本專題-判斷對象里面是否是類字符串(推薦使用isinstance(obj,str))
- 輕松python文本專題-字符串對齊
- 輕松python文本專題-去掉字符串前后空格
- 輕松python文本專題-拼接、合并字符串
- 輕松python文本專題-字符串逐字符反轉以及逐單詞反轉
- 輕松python文本專題-maketrans和translate
- 輕松python文本專題-字符串開頭或者結尾匹配