国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Python基于template實現字符串替換

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

下面介紹使用python字符串替換的方法;

1. 字符串替換

將需要替換的內容使用格式化符替代,后續補上替換內容;

template = 'hello %s , your website is %s ' % ('大CC','http://blog.me115.com')print(template)

也可使用format函數完成:

template = 'hello {0} , your website is {1} '.format('大CC','http://blog.me115.com')print(template)

注:該方法適用于變量少的單行字符串替換;

2. 字符串命名格式化符替換

使用命名格式化符,這樣,對于多個相同變量的引用,在后續替換只用申明一次即可;

template = 'hello %(name)s ,your name is %(name), your website is %(message)s' %{'name':'大CC','message':'http://blog.me115.com'}print(template)

使用format函數的語法方式:

template = 'hello {name} , your name is {name}, your website is {message} '.format(name='大CC',message='http://blog.me115.com')print(template)

注:適用相同變量較多的單行字符串替換;

3.模版方法替換

使用string中的Template方法;

通過關鍵字傳遞參數:

from string import TemplatetempTemplate = Template('Hello $name ,your website is $message')print(tempTemplate.substitute(name=’大CC’,message=’http://blog.me115.com’))

通過字典傳遞參數:

from string import Template

tempTemplate = Template('There $a and $b')d={’a’:’apple’,’b’:’banbana’}print(tempTemplate.substitute(d))

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 永安市| 扎赉特旗| 西藏| 工布江达县| 宜春市| 满洲里市| 内黄县| 盘山县| 乌拉特前旗| 任丘市| 南昌县| 景德镇市| 宁德市| 隆化县| 虎林市| 罗平县| 天长市| 左权县| 哈密市| 东明县| 锡林浩特市| 荆州市| 义马市| 闻喜县| 昭通市| 二连浩特市| 都匀市| 航空| 兖州市| 鲁山县| 武强县| 镇沅| 全南县| 伊金霍洛旗| 潞西市| 鸡东县| 横山县| 余江县| 瓦房店市| 澜沧| 洛浦县|