久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python基于template實(shí)現(xiàn)字符串替換

瀏覽:52日期:2022-07-04 09:58:52

下面介紹使用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)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 赤壁市| 莒南县| 绥化市| 英超| 沂源县| 桓台县| 大洼县| 宜兰市| 米泉市| 巴东县| 南京市| 克拉玛依市| 吴桥县| 蓬安县| 木兰县| 长葛市| 华亭县| 泰兴市| 太湖县| 曲水县| 久治县| 义乌市| 高邮市| 铜山县| 梨树县| 泰顺县| 孙吴县| 紫阳县| 手游| 秀山| 灵山县| 隆安县| 驻马店市| 巨野县| 临安市| 佛坪县| 涟源市| 翼城县| 芒康县| 石家庄市| 茌平县|