Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python how to convert from string.template object to string

This is very simple.I am sure I am missing something silly.

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 in intepreter directly,I get the proper output. But when I run it from a file.I get <string.Template object at 0x012D33B0>.How do I convert from string.Template object to string.I have tried str(html).By the bye wasn't print statement supposed to do that(string conversion) ?

like image 733
Jibin Avatar asked Nov 28 '11 07:11

Jibin


People also ask

How do I use a string template in Python?

The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. This class has 2 key methods: substitute(mapping, **kwds): This method performs substitutions using a dictionary with a process similar to key-based mapping objects.

What is ${} in Python?

It uses Template class from string module. It has a syntax somewhat similar to . format() when done with keywords, but instead of curly braces to define the placeholder, it utilises a dollar sign ($). ${} is also valid and should be in place when a valid string comes after the placeholder.

What syntax does Python use to replace items in a template?

The substitute() Method This method replaces the placeholders in a template string using keyword arguments or using a mapping containing identifier-value pairs.


2 Answers

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

print html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
like image 195
wutz Avatar answered Oct 30 '22 07:10

wutz


According to the docs you should take the return Value of 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 
like image 23
Pengman Avatar answered Oct 30 '22 08:10

Pengman