模板字符串(python基于template实现字符串替换)

1. 字符串替换

将需要替换的内容使用格式化符替代,后续补上替换内容:

template = "hello %s , your website is %s " % ("大JJ", "https://mp.weixin.qq.com/s/mrZdM9ZuT7VA3JXLeLTPuQ")

print(template)  # hello 大JJ , your website is https://mp.weixin.qq.com/s/mrZdM9ZuT7VA3JXLeLTPuQ 

也可使用format函数完成:【0、1可以作为标注被多个字符串替换的位置】

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

print(template)  # hello 大CC , your website is http://blog.me115.com

2. 字符串命名格式化符替换:【适用于相同变量较多的单行字符串替换】

使用命名格式化符,这样,对于多个相同变量的引用,在后续替换只用申明一次即可;

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

print(template)  # hello 大CC ,your name is 大CC, your website is http://blog.me115.com

使用format函数的语法方式:

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

3.模版方法替换

使用 string 模块中的 Template 方法;

①通过关键字传递参数:

from string import Template

tempTemplate = Template("Hello $name ,your website is $message")

print(tempTemplate.substitute(name='大CC', message='http://blog.me115.com'))  # Hello 大CC ,your website is http://blog.me115.com

②通过字典传递参数:

from string import Template

tempTemplate = Template("There $a and $b")

print(tempTemplate.substitute({'a': 'apple', 'b': 'banbana'}))  # There apple and banbana

 

posted @   习久性成  阅读(2322)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示