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開(kāi)發(fā)必須掌握的Pip使用全攻略
在這篇文章中,我們將深入探討Python的主要包管理工具——Pip,包括Pip的基本概念、安裝和配置、中國(guó)國(guó)內(nèi)鏡像源的使用等,需要的可以參考一下2023-07-07
Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例
本篇文章主要介紹了Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
python實(shí)現(xiàn)測(cè)試工具(一)——命令行發(fā)送get請(qǐng)求
這篇文章主要介紹了python如何實(shí)現(xiàn)命令行發(fā)送get請(qǐng)求,幫助大家更好的利用python進(jìn)行測(cè)試工作,感興趣的朋友可以了解下2020-10-10
如何用C代碼給Python寫(xiě)擴(kuò)展庫(kù)(Cython)
這篇文章主要介紹了如何用C代碼給Python寫(xiě)擴(kuò)展庫(kù)(Cython),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05
Python輕松寫(xiě)個(gè)課堂隨機(jī)點(diǎn)名系統(tǒng)
現(xiàn)在的學(xué)生大部分都很積極,會(huì)主動(dòng)舉手回答問(wèn)題。但是,也會(huì)遇到一些不好的情況,比如年級(jí)越高主動(dòng)舉手的人越少,所以本文寫(xiě)了一個(gè)隨機(jī)的學(xué)生點(diǎn)名系統(tǒng)可以幫老師解決這些問(wèn)題2023-01-01
python實(shí)現(xiàn)socket客戶(hù)端和服務(wù)端簡(jiǎn)單示例
這篇文章主要介紹了python實(shí)現(xiàn)socket客戶(hù)端和服務(wù)端簡(jiǎn)單示例,需要的朋友可以參考下2014-02-02
Django利用cookie保存用戶(hù)登錄信息的簡(jiǎn)單實(shí)現(xiàn)方法
這篇文章主要介紹了Django利用cookie保存用戶(hù)登錄信息的簡(jiǎn)單實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Django框架使用cookie保存用戶(hù)信息的相關(guān)操作技巧,需要的朋友可以參考下2019-05-05
Pandas?DataFrame列快速轉(zhuǎn)換為列表(3秒學(xué)會(huì)!)
這篇文章主要給大家介紹了關(guān)于Pandas?DataFrame列如何快速轉(zhuǎn)換為列表的相關(guān)資料,在Python的pandas庫(kù)中可以使用DataFrame的tolist()方法將DataFrame轉(zhuǎn)化為列表,需要的朋友可以參考下2023-10-10

