Python如何将string.template对象转换为字符串?

17

这很简单。我相信我错过了一些愚蠢的东西。

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),顺便问一句,print 语句不应该可以实现这个(字符串转换)吗?
3个回答

19

safe_substitute方法会返回一个字符串,其中包含了所做的替换。使用该方法可以让你在多个替换中重复使用同一个模板。因此,你需要这样编写代码:

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

5

根据文档,你应该使用safe_substitute的返回值

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

2

通过 safe_substitute 方法返回的结果:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接