python Template中substitute()的使用


在python中Template可以將字符串的格式固定下來,重復利用。

Template屬於string中的一個類,要使用他的話可以用以下方式調用:

from string import Template

我們使用以下代碼:

>>> s = Template('There  ${moneyType} is  ${money}')
>>> print s.substitute(moneyType = 'Dollar',money=12)

運行結果顯示“There  Dollar is  12”

這樣我們就可以替換其中的數據了。

但是我們要替換其中的一個數據呢?

>>> print s.substitute(moneyType = 'Dollar')

Traceback (most recent call last):
  File "<pyshell#509>", line 1, in <module>
    print s.substitute(moneyType = 'Dollar')
  File "C:\Python27\lib\string.py", line 172, in substitute
    return self.pattern.sub(convert, self.template)
  File "C:\Python27\lib\string.py", line 162, in convert
    val = mapping[named]
KeyError: 'money'

報錯了。看來這樣不行。

這是就要用到safe_substitute了

>>> print s.safe_substitute(moneyType = 'Dollar')
There  Dollar is  ${money}

注意:我之前看的參考書$符后使用的是“()”括號,但是我在2.7.9上運行報錯,后來試了一下,冒失后面的版本不支持“()”。使用“{}”或是不寫括號是沒有問題的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM