Python String Formatting

From the Python 3 documentation

The formatting operations described here (% operator) exhibit a variety of quirks that lead to a number of common errors [...]. Using the newer formatted string literals [...] helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.

% operator

Prefer String Literals

For new code, using str.format, or formatted string literals (Python 3.6+) over the % operator is strongly recommended.

>>> name = 'Pete'
>>> 'Hello %s' % name
# "Hello Pete"

We can use the %x format specifier to convert an int value to a string:

>>> num = 5
>>> 'I have %x apples' % num
# "I have 5 apples"

str.format

Python 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.

>>> name = 'John'
>>> age = 20'

>>> "Hello I'm {}, my age is {}".format(name, age)
# "Hello I'm John, my age is 20"

>>> "Hello I'm {0}, my age is {1}".format(name, age)
# "Hello I'm John, my age is 20"

Formatted String Literals or f-strings

If your are using Python 3.6+, string f-strings are the recommended way to format strings.

From the Python 3 documentation

A formatted string literal or f-string is a string literal that is prefixed with `f` or `F`. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.

>>> name = 'Elizabeth'
>>> f'Hello {name}!'
# 'Hello Elizabeth!'

It is even possible to do inline arithmetic with it:

>>> a = 5
>>> b = 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
# 'Five plus ten is 15 and not 30.'

Template Strings

A simpler and less powerful mechanism, but it is recommended when handling 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!'