0

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 loop
  • string.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?

J...S
  • 5,079
  • 1
  • 20
  • 35
  • @larsks Thanks for the link. But I hope someone knows something clear especially about security against execution of random code or something. – J...S Jan 18 '20 at 15:36
  • 2
    The template functions in the strings library simply predates template strings and has continued to be maintained. It is no safer (in fact - note the warning in [safe_substitute](https://docs.python.org/3.8/library/string.html#string.Template.safe_substitute) method) and lacks the rich functionality. They *may* be safer with user supplied format strings [link](https://realpython.com/python-string-formatting/#4-template-strings-standard-library) but I would not count on that. – dawg Jan 18 '20 at 15:50

0 Answers0