Python基于template實(shí)現(xiàn)字符串替換
下面介紹使用python字符串替換的方法;
1. 字符串替換
將需要替換的內(nèi)容使用格式化符替代,后續(xù)補(bǔ)上替換內(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. 字符串命名格式化符替換
使用命名格式化符,這樣,對(duì)于多個(gè)相同變量的引用,在后續(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ù)的語(yǔ)法方式:
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ò)關(guān)鍵字傳遞參數(shù):
from string import TemplatetempTemplate = Template('Hello $name ,your website is $message')print(tempTemplate.substitute(name=’大CC’,message=’http://blog.me115.com’))
通過(guò)字典傳遞參數(shù):
from string import Template
tempTemplate = Template('There $a and $b')d={’a’:’apple’,’b’:’banbana’}print(tempTemplate.substitute(d))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用CSS制作3D動(dòng)畫(huà)2. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例3. asp畫(huà)中畫(huà)廣告插入在每篇文章中的實(shí)現(xiàn)方法4. 熊海CMS代碼審計(jì)漏洞分析5. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera6. ASP編碼必備的8條原則7. WMLScript腳本程序設(shè)計(jì)第1/9頁(yè)8. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)9. asp中Request.ServerVariables的參數(shù)集合10. PHP session反序列化漏洞深入探究
