这很简单。我确定我漏掉了一些愚蠢的东西。
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/