python 如何从 string.template 对象转换为字符串

标签 python string templates

这很简单。我确定我漏掉了一些愚蠢的东西。

fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb')        
html = Template(fp.read())
fp.close()
html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print html 

当我直接在解释器中运行这段代码时,我得到了正确的输出。 但是当我从一个文件运行它时。我得到 <string.Template object at 0x012D33B0> .如何从 string.Template 对象转换为字符串。我试过 str(html) .顺便说一句,打印语句不应该这样做(字符串转换)吗?

最佳答案

safe_substitute 返回,作为一个字符串,带有替换的模板。这样,您可以重复使用同一模板进行多次替换。所以你的代码必须是

print html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')

关于python 如何从 string.template 对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8292555/

相关文章:

python - 带有单个数组和/或empty_like 的numpy 的Where 子句

python - 如何将字符串转换为单个字符元组列表?

python - Boto3:配置文件位置

c++ - 从一组字符串派生 RegExp

java - 尝试使用字符数组解密字符串(Polybius Square)

Python:创建后卡住字典键

Php函数展开化学方程式

c++ - 我可以使用非模板类专门化可变参数模板模板参数吗?

javascript - 如何在使用 fastify 服务之前替换 Javascript 变量?

c++ - 如何实现自动插入隐含占位符的 easy_bind()?