A guide to comparing the syntax of different formatting styles.

Resources

Modern format style

name = "World"

"Hello, {}!" % name
# 'Hello, World!'
foo = "abc"
bar = 123

"{} {}".format(foo, bar)
# 'abc - 123'

See more info in the String Format section.

Old format style

Using % as in C. Avoid using this style.

e.g.

foo = "World"

"Hello, %s!" % foo
# 'Hello, World!'
foo = "abc"
bar = 123

"%s - %s" % (foo, bar)
# 'abc - 123'

Debugging

Using the %s style is the standard approach still for the built-in logging module.

logging.debug("User name: %s", name)

Template strings

I have rarely come across this. This uses the Template class constructor.

A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.

from string import Template


name = 'Elizabeth'
t = Template('Hey $name!')
t.substitute(name=name)
# => 'Hey Elizabeth!'