python 如何将 string.template 对象转换为字符串
这很简单。我肯定我漏掉了什么小问题。
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)
。顺便问一下,打印语句不是应该能做到这个(字符串转换)吗?
3 个回答
2
结果是通过 safe_substitute 方法返回的:
result = html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print result
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
19
safe_substitute
返回一个字符串,这个字符串是经过替换后的模板。这样,你就可以用同一个模板进行多次替换。所以你的代码需要是
print html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')