Python how to convert from string.template object to string

It is very simple. I'm sure I'm missing something stupid.

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

When I run this code directly in intrereter, I get the correct output. But when I run it from a file. I get <string.Template object at 0x012D33B0> . How do I convert from a string.Template object to a string. I tried str(html) .By so far no print statement has been specified that should do this (string conversion)

+6
source share
3 answers

safe_substitute returns , as a string, a template with the replacements made. This way you can reuse the same template for multiple substitutions. So your code should be

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

According to docs you should take safe_substitute return value

 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
source

The result is returned by the safe_substitute method:

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

Source: https://habr.com/ru/post/902520/


All Articles