advanced string formatting vs template strings

Viewed 40802
6 Answers

This is old but it is worth mentioning that one great advantage of using Template Strings is that it is safe when you are accepting the template from un-trusted source. This can be from a configuration file for instance.

Here is an example from this article:

CONFIG = {"SECRET_KEY": "super secret key"}

class Event:
    def __init__(self, id_, level, message):
        self.id_ = id_
        self.level = level
        self.message = message

def format_event(format_string, event):
    return format_string.format(event=event)


# user supplied template
inp = "{event.__init__.__globals__[CONFIG][SECRET_KEY]}"

event = Event(1234, "foo", "boo")
print(format_event(inp, event))

output:

super secret key

Adding to the other answers: one advantage of template strings vs. format strings is that often, the characters {} are more likely to naturally occur in a piece of text than $foo or ${foo} (e.g. when generating source code). That means that with templates, you need to spend less effort in escaping these occurrences of proper text.

Related