本文實例講述了Python編程之字符串模板(Template)用法。分享給大家供大家參考,具體如下:
#coding=utf8'''''字符串格式化操作符,需要程序員明確轉換類型參數,比如到底是轉成字符串、整數還是其他什么類型。新式的字符串模板的優勢是不用去記住所有相關細節,而是像shell風格的腳本語言里面那樣使用美元符號($).由于新式的字符串引進Template對象,Template對象有兩個方法:substitute()、safe_substitute()。substitute()更為嚴謹,在key缺少的情況下會報一個KeyError的異常。safe_substitute()在缺少key的情況下,直接原封不動的把字符串顯示出來。'''#導入Template對象from string import Templatedef stringTemplate():  #創建一個Template實例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輸出    #并給相應key賦值    Substitute= tmp.substitute(yuan=yu,how=yu)    print Substitute  print  for yu in yuanList:    #使用substitute函數缺少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的情況下    #直接原封不動的把字符串顯示出來。    safe_substitute= tmp.safe_substitute(yuan=yu)    print safe_substitute  print#調用stringTemplate函數stringTemplate()運行結果:

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》及《Python入門與進階經典教程》。
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答