gpt4 book ai didi

python - 为字符串格式添加自定义转换类型

转载 作者:太空狗 更新时间:2023-10-29 21:14:45 24 4
gpt4 key购买 nike

python 中是否有为字符串格式添加额外的转换类型?

基于 % 的字符串格式化中使用的标准转换类型是 s 用于字符串,d 用于小数等。我想要做的是添加一个新字符,我可以为其指定一个自定义处理程序(例如 lambda 函数),该处理程序将返回要插入的字符串。

例如,我想添加 h 作为转换类型,以指定应该对字符串进行转义以便在 HTML 中使用。例如:

#!/usr/bin/python

print "<title>%(TITLE)h</title>" % {"TITLE": "Proof that 12 < 6"}

这将在 "TITLE" 上使用 cgi.escape 产生以下输出:

<title>Proof that 12 &lt; 6</title>

最佳答案

您可以为 html 模板创建自定义格式化程序:

import string, cgi

class Template(string.Formatter):
def format_field(self, value, spec):
if spec.endswith('h'):
value = cgi.escape(value)
spec = spec[:-1] + 's'
return super(Template, self).format_field(value, spec)

print Template().format('{0:h} {1:d}', "<hello>", 123)

请注意,所有转换都在模板类内部进行,不需要更改输入数据。

关于python - 为字符串格式添加自定义转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19864302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com