I was trying string templating and came across Template
class.
I could not figure out the advantage of using this instead of a simple str.format()
.
For example, both
s = "hello {name}"
print(s.format(name="Nick"))
and
from string import Template
s = Template("hello $name")
print(s.substitute(name="Nick"))
seems to do the same thing.
I ran a timeit and str.format()
seems to be faster.
str.format()
: 500000 loops, best of 5: 564 nsec per loopstring.Template
: 50000 loops, best of 5: 5.03 usec per loop
Is there any advantage of using string.Template()
instead of simple str.format()
then?
Edit: Could template strings be more secure or something?