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 Template
tempTemplate = 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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)多張圖片合成一張馬賽克圖片
這篇文章主要介紹了了Python如何實(shí)現(xiàn)將多張圖片合成一張馬賽克圖片。文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的可以學(xué)習(xí)一下2021-12-12通過(guò)mod_python配置運(yùn)行在Apache上的Django框架
這篇文章主要介紹了通過(guò)mod_python配置運(yùn)行在Apache上的Django框架,Django是最具人氣的Python web開(kāi)發(fā)框架,需要的朋友可以參考下2015-07-07Pandas.DataFrame刪除指定行和列(drop)的實(shí)現(xiàn)
本文主要介紹了Pandas.DataFrame刪除指定行和列(drop)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02詳解Numpy數(shù)組轉(zhuǎn)置的三種方法T、transpose、swapaxes
這篇文章主要介紹了詳解Numpy數(shù)組轉(zhuǎn)置的三種方法T、transpose、swapaxes,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05python+matplotlib演示電偶極子實(shí)例代碼
這篇文章主要介紹了python+matplotlib演示電偶極子實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01Python數(shù)據(jù)分析與處理(二)——處理中國(guó)地區(qū)信息
這篇文章主要介紹了Python數(shù)據(jù)分析與處理-處理中國(guó)地區(qū)信息,上文介紹了北京高考分?jǐn)?shù)線統(tǒng)計(jì)分析,這篇文章依然圍繞Python數(shù)據(jù)分析與處理的相關(guān)資料來(lái)介紹處理中國(guó)地區(qū)信息,需要的朋友可以參考一下2021-12-12