本文實(shí)例講述了Python編程之字符串模板(Template)用法。分享給大家供大家參考,具體如下:
#coding=utf8'''''字符串格式化操作符,需要程序員明確轉(zhuǎn)換類型參數(shù),比如到底是轉(zhuǎn)成字符串、整數(shù)還是其他什么類型。新式的字符串模板的優(yōu)勢(shì)是不用去記住所有相關(guān)細(xì)節(jié),而是像shell風(fēng)格的腳本語(yǔ)言里面那樣使用美元符號(hào)($).由于新式的字符串引進(jìn)Template對(duì)象,Template對(duì)象有兩個(gè)方法:substitute()、safe_substitute()。substitute()更為嚴(yán)謹(jǐn),在key缺少的情況下會(huì)報(bào)一個(gè)KeyError的異常。safe_substitute()在缺少key的情況下,直接原封不動(dòng)的把字符串顯示出來(lái)。'''#導(dǎo)入Template對(duì)象from string import Templatedef stringTemplate(): #創(chuàng)建一個(gè)Template實(shí)例tmp tmp=Template("I have ${yuan} yuan,I can buy ${how} hotdog") yuanList=[1,5,8,10,12,13] for yu in yuanList: #substitute()按照Template中string輸出 #并給相應(yīng)key賦值 Substitute= tmp.substitute(yuan=yu,how=yu) print Substitute print for yu in yuanList: #使用substitute函數(shù)缺少key值包KeyError try: lackHow= tmp.substitute(yuan=yu) print lackHow print except KeyError,e: print "substitute lack key ",e print for yu in yuanList: #safe_substitute()在缺少key的情況下 #直接原封不動(dòng)的把字符串顯示出來(lái)。 safe_substitute= tmp.safe_substitute(yuan=yu) print safe_substitute print#調(diào)用stringTemplate函數(shù)stringTemplate()運(yùn)行結(jié)果:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選