脚本专栏 
首页 > 脚本专栏 > 浏览文章

Python基于template实现字符串替换

(编辑:jimmy 日期: 2025/3/4 浏览:3 次 )

下面介绍使用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 Template
tempTemplate = 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))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:python3.7中安装paddleocr及paddlepaddle包的多种方法
下一篇:使用Python画了一棵圣诞树的实例代码
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 站点导航 SiteMap