Python基于template實現字符串替換
下面介紹使用python字符串替換的方法;
1. 字符串替換
將需要替換的內容使用格式化符替代,后續補上替換內容;
template = 'hello %s , your website is %s ' % ('大CC','http://blog.me115.com')print(template)
也可使用format函數完成:
template = 'hello {0} , your website is {1} '.format('大CC','http://blog.me115.com')print(template)
注:該方法適用于變量少的單行字符串替換;
2. 字符串命名格式化符替換
使用命名格式化符,這樣,對于多個相同變量的引用,在后續替換只用申明一次即可;
template = 'hello %(name)s ,your name is %(name), your website is %(message)s' %{'name':'大CC','message':'http://blog.me115.com'}print(template)
使用format函數的語法方式:
template = 'hello {name} , your name is {name}, your website is {message} '.format(name='大CC',message='http://blog.me115.com')print(template)
注:適用相同變量較多的單行字符串替換;
3.模版方法替換
使用string中的Template方法;
通過關鍵字傳遞參數:
from string import TemplatetempTemplate = Template('Hello $name ,your website is $message')print(tempTemplate.substitute(name=’大CC’,message=’http://blog.me115.com’))
通過字典傳遞參數:
from string import Template
tempTemplate = Template('There $a and $b')d={’a’:’apple’,’b’:’banbana’}print(tempTemplate.substitute(d))
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. jsp+servlet簡單實現上傳文件功能(保存目錄改進)2. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程3. 一款功能強大的markdown編輯器tui.editor使用示例詳解4. java獲取文件編碼,jsoup獲取html純文本操作5. 利用CSS制作3D動畫6. python 寫函數在一定條件下需要調用自身時的寫法說明7. 淺談Android Studio導出javadoc文檔操作及問題的解決8. Java GZip 基于內存實現壓縮和解壓的方法9. Python 實現勞拉游戲的實例代碼(四連環、重力四子棋)10. 存儲于xml中需要的HTML轉義代碼
