現在我們就格式化方法做一個詳細一點的交代。
基本的操作
所謂格式化方法,就是可以先建立一個輸出字符串的模板,然后用format來填充模板的內容。
代碼如下:
>>> #先做一個字符串模板
>>> template = "My name is {0}. My website is {1}. I am writing {2}."
>>> #用format依次對應模板中的序號內容
>>> template.format("qiwsir","qiwsir.github.io","python")
'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'
當然,上面的操作如果你要這樣做,也是可以的:
代碼如下:
>>> "My name is {0}. My website is {1}. I am writing {2}.".format("qiwsir","qiwsir.github.io","python")
'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'
這些,跟用%寫的表達式沒有什么太大的區別。不過看官別著急,一般小孩子都區別不到,長大了才有區別的。慢慢看,慢慢實驗。
除了可以按照對應順序(類似占位符了)填充模板中的位置之外,還能這樣,用關鍵字來指明所應該田中的內容。
代碼如下:
>>> template = "My name is {name}. My website is {site}"
>>> template.format(site='qiwsir.github.io', name='qiwsir')
'My name is qiwsir. My website is qiwsir.github.io'
關鍵詞所指定的內容,也不一定非是str,其它的數據類型也可以。此外,關鍵詞和前面的位置編號,還可以混用。比如:
代碼如下:
>>> "{number} is in {all}. {0} are my number.".format("seven",number=7,all=[1,2,3,4,5,6,7,8,9,0])
'7 is in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]. seven are my number.'
是不是開始感覺有點意思了?看輸出結果,就知道,經過format方法得到是一個新的str。
序列對象的偏移量
有這樣一個要求:在輸出中,顯示出一個單詞的第一個字母和第三個個字母。比如單詞python,要告訴看官,第一字母是p,第三個字母是t。
這個問題并不難。實現方法也不少,這里主要是要展示一下偏移量在format中的應用。
代碼如下:
>>> template = "First={0[0]}, Third={0[2]}"
>>> template.format(word)
'First=p, Third=t'
list也是序列類型的,其偏移量也可。
代碼如下:
>>> word_lst = list(word)
>>> word_lst
['p', 'y', 't', 'h', 'o', 'n']
>>> template
'First={0[0]}, Third={0[2]}'
>>> template.format(word_lst)
'First=p, Third=t'
對上面的綜合一下,稍微啰嗦一點的實驗:
代碼如下:
>>> template = "The word is {0}, Its first is {0[0]}. Another word is {1}, Its second is {1[1]}."
>>> template.format("python","learn")
'The word is python, Its first is p. Another word is learn, Its second is e.'
新聞熱點
疑難解答