Python基于template實現(xiàn)字符串替換
下面介紹使用python字符串替換的方法;
1. 字符串替換
將需要替換的內(nèi)容使用格式化符替代,后續(xù)補上替換內(nèi)容;
template = 'hello %s , your website is %s ' % ('大CC','http://blog.me115.com')print(template)
也可使用format函數(shù)完成:
template = 'hello {0} , your website is {1} '.format('大CC','http://blog.me115.com')print(template)
注:該方法適用于變量少的單行字符串替換;
2. 字符串命名格式化符替換
使用命名格式化符,這樣,對于多個相同變量的引用,在后續(xù)替換只用申明一次即可;
template = 'hello %(name)s ,your name is %(name), your website is %(message)s' %{'name':'大CC','message':'http://blog.me115.com'}print(template)
使用format函數(shù)的語法方式:
template = 'hello {name} , your name is {name}, your website is {message} '.format(name='大CC',message='http://blog.me115.com')print(template)
注:適用相同變量較多的單行字符串替換;
3.模版方法替換
使用string中的Template方法;
通過關(guān)鍵字傳遞參數(shù):
from string import TemplatetempTemplate = Template('Hello $name ,your website is $message')print(tempTemplate.substitute(name=’大CC’,message=’http://blog.me115.com’))
通過字典傳遞參數(shù):
from string import Template
tempTemplate = Template('There $a and $b')d={’a’:’apple’,’b’:’banbana’}print(tempTemplate.substitute(d))
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲2. jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)3. JavaScript實現(xiàn)組件化和模塊化方法詳解4. ASP.NET MVC遍歷驗證ModelState的錯誤信息5. HTML5 Canvas繪制圖形從入門到精通6. .Net Core和RabbitMQ限制循環(huán)消費的方法7. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達式8. SpringMVC+Jquery實現(xiàn)Ajax功能9. ASP中if語句、select 、while循環(huán)的使用方法10. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明
