模板字符串(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 @ 2021-11-25 14:27  习久性成  阅读(1735)  评论(0编辑  收藏  举报