打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用 Python Template类格式化字符串
userphoto

2023.11.04 甘肃

关注

使用 Python 模板类格式化字符串

参考之间的文章

Python 字符串格式化最佳实践:f str, format % Template

介绍

Python已经提供了许多替换字符串的方法,包括最近推出的f-Strings。虽然用模板替换字符串不太常见,但它的强大之处在于我们如何自定义字符串格式规则。

使用 Python 的Template类格式化字符串。

了解 Python Template 类

下面是如何在代码中使用 Python 类的基本示例:Template

>>> from string import Template>>> temp_str = 'Hi $name, welcome to $site'>>> temp_obj = Template(temp_str)>>> temp_obj.substitute(name='John Doe', site='StackAbuse.com')'Hi John Doe, welcome to StackAbuse.com'

构建模板字符串时,我们使用两个占位符 $name 和$site' 符号执行实际替换 $

模板字符串

模板字符串是包含特殊占位符的常规 Python 字符串。正如之前看到的,这些占位符是使用符号以及有效的 Python 标识符创建的。一旦有了有效的模板字符串,占位符就可以替换为自己的值,

>>> budget = Template('The $time budget for investment is $$$amount')>>> budget.substitute(time='monthly', amount='1,000.00')'The monthly budget for investment is $1,000.00'
>>> template = Template('$what, $who!')>>> template.substitute(what='Hello', who='World')'Hello, World!'

使用:_ 来连接多个占位符的字符串

>>> filename_temp = Template('$code_$product_$batch.xlsx')>>> filename_temp.substitute(code='001', product='Apple_Juice', batch='zx.001.2020')Traceback (most recent call last):  ...KeyError: 'code_'
>>> filename_temp = Template('${code}_${product}_$batch.xlsx')>>> filename_temp.substitute(code='001', product='Apple_Juice', batch='zx.001.2020')'001_Apple_Juice_zx.001.2020.xlsx'
>>> template = Template('$what, $who!')  # Original template>>> template.template = 'My $what, $who template'  # Modified template>>> template.template'My $what, $who template'>>> template.substitute(what='Hello', who='World')'My Hello, World template'

substitute() 方法

实际就是将占位符替换成目标的字符串,使用一个字典来批量替换点开位符中的内容。

>>> template = Template('Hi $name, welcome to $site')>>> mapping = {'name': 'John Doe', 'site': 'StackAbuse.com'}>>> template.substitute(**mapping)'Hi John Doe, welcome to StackAbuse.com'

常见模板错误

在使用 Python 类时一些常见错误。Template

例如提供一组不完整的参数时,都会引发异常。

>>> template = Template('Hi $name, welcome to $site')>>> template.substitute(name='Jane Doe')Traceback (most recent call last):  ...KeyError: 'site'

使用无效标识符作为占位符

$0name 注意这个因此name前面有个数学 0,是不合法的。

>>> template = Template('Hi $0name, welcome to $site')>>> template.substitute(name='Jane Doe', site='StackAbuse.com')Traceback (most recent call last): ...ValueError: Invalid placeholder in string: line 1, col 4

safe_substitute() 方法

缺少或不匹配的占位符,在最终字符串中保持不变。

>>> template = Template('Hi $name, welcome to $site')>>> template.safe_substitute(name='John Doe')'Hi John Doe, welcome to $site'

自定义 Python 模板类

Python 类是为子类化和自定义而设计的。这允许修改类的正则表达式模式

使用不同的分隔符

默认使用 $ 来表示占位符,也可以换成 其他的 如 #

from string import Templateclass MyTemplate(Template): delimiter = '#'template = MyTemplate('Hi #name, welcome to #site')print(template.substitute(name='Jane Doe', site='StackAbuse.com'))# Output:# 'Hi Jane Doe, welcome to StackAbuse.com'# Escape operations also worktag = MyTemplate('This is a Twitter hashtag: ###hashtag')print(tag.substitute(hashtag='Python'))# Output:# 'This is a Twitter hashtag: #Python'

更改符合标识符条件的内容

from string import Templateclass MyTemplate(Template):    idpattern = r'(?-i:[a-zA-Z][a-zA-Z]*)'# Underscores are not allowedtemplate = MyTemplate('$name_underscore not allowed')print(template.substitute(name_underscore='Jane Doe'))
Traceback (most recent call last): ...KeyError: 'name'

可以让数字也是不合法的:

template = MyTemplate('$python3 digits not allowed')print(template.substitute(python3='Python version 3.x'))

错误将是:

Traceback (most recent call last): ...KeyError: 'python'

使用 eval() 和 exec() 运行代码

注意:内置函数 eval() 和 exec() 在与恶意输入一起使用时可能会产生重要的安全隐患。谨慎使用!

>>> template = Template('[$exp for item in $coll]')>>> eval(template.substitute(exp='item ** 2', coll='[1, 2, 3, 4]'))[1, 4, 9, 16]>>> eval(template.substitute(exp='2 ** item', coll='[3, 4, 5, 6, 7, 8]'))[8, 16, 32, 64, 128, 256]>>> import math>>> eval(template.substitute(expression='math.sqrt(item)', collection='[9, 16, 25]'))[3.0, 4.0, 5.0]

由于模板字符串的复杂程度没有限制,因此可以创建包含任何 Python 代码的模板字符串

from string import Template_class_template = '''class ${klass}: def __init__(self, name): self.name = name def ${method}(self): print('Hi', self.name + ',', 'welcome to', '$site')'''template = Template(_class_template)exec(template.substitute(klass='MyClass', method='greet', site='StackAbuse.com'))obj = MyClass('John Doe')obj.greet()

在这里,创建一个模板字符串来保存一个功能齐全的 Python 类。

结论

其实Template类有一个重要的 特性就是 j安全性。原因可看

#妙笔生花创作挑战#

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Python 标准库学习 --- string
Python标准库概览(1):string
说说Python有几种字符串格式化?
用 Python 的 Template 类生成文件报告
当程序员遇到它,彻底疯狂了!
为什么 Python 的 f-string 可以连接字符串与数字?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服